Java Tutorial #5 – Loop Statements

While Statement, Do-While Statement, For Statement, For-Each Statement

Table of Contents

Iteration statements are used to repeat a particular block of code until a certain condition is true. In this article, we will be taking a look at Java’s iteration statements.

While Statement

The while statement repeats a block of code as long as a condition is true.

Syntax

A while statement has the following syntax:

while (condition){
//body of the loop
}

The while keyword is followed by a condition that evaluates to a boolean value. If the boolean value is true, the while loop is entered. Once the code in the loop is completed, the condition is checked again and this continues till the condition becomes false.

Example

The following code demonstrates a basic while statement:

int i = 0;

while (i < 3) {
System.out.println("Loop Iteration: " + i);
	i++;
}
System.out.println("Done!");

Here, the while statement checks if i is less than 3. Since this is true, the loop is entered and the System.out statement is executed. i is then incremented in the while loop and the condition is checked again. This goes on till the value of i becomes 3 after which the loop is exited. So, this code produces the following output:

Loop Iteration: 0
Loop Iteration: 1
Loop Iteration: 2
Done!

Do-while Statement

A do-while loop is similar to a while loop except that it checks the condition at the end of the loop. This ensures that the body of the loop is executed at least once.

Syntax

do{
// body of the loop
} while(condition);

The do keyword is followed by some code followed by a while statement. A condition that evaluates to a boolean value is specified in the while statement. The loop first executes and then checks the condition. If the condition is true, the loop is repeated. The loop is exited when the condition becomes false.

Example

The following code demonstrates a basic do-while statement:

int i = 0;

do {
System.out.println("Loop Iteration: " + i);
	i++;
} while (i < 3);
		
System.out.println("Done!");
This code is similar to the code above except that it uses a do-while loop. So, it produces the same output as before. 
However, consider the following code:
int i = 5;

do {
System.out.println("Loop Iteration: " + i);
	i++;
} while (i < 3);
		
System.out.println("Done!");

In this case, i is initialized to the value 5. Since the do-while loop checks the condition at the end, the body of the loop is executed once. After that, the condition is checked and since it is false, the loop is not entered again. So, this code produces the following output:

Loop Iteration: 5
Done!

If a while loop had been used here, the body of the loop would not have been executed even once since the condition is false.

For Statement

A for loop can be used to iterate over a range of values. It continues the iteration until a condition is true, after which the loop is exited.

Syntax

for(initialization;condition;iteration){
//body of the loop
}

The for keyword is followed by an initialization statement, a condition and an iteration statement. The initialization statement executes only once, at the start of the loop. The condition and iteration parts are executed each time the loop is repeated. The condition statement evaluates to a boolean value. If it is true, the body of the loop is executed. Once the body completes, the iteration part is executed and the condition is again checked. This continues till the condition evaluates to false. 

Example

The following code demonstrates a basic for statement:

for(int i = 0;i < 3;i++) {
System.out.println("Loop Iteration: " + i);
}
System.out.println("Done!");

Here i=0 is the initialization part, i < 3 is the condition and i++ is the iteration part. The for loop initializes i to 0 at the start of the loop. It then checks if i<3 is true and since this is true, it enters the loop. Once the code it in the loop completes, it increments i and again checks if the condition i<3 is true. This continues till i becomes 3 after which the loop is exited. So, this code produces the following output:

Loop Iteration: 0
Loop Iteration: 1
Loop Iteration: 2
Done!

For-Each Statement

The for-each loop is used to cycle through an array or a collection of objects.

Syntax

for(datatype var : collection) {
//body of the loop
}

The for keyword is followed by a variable and the collection over which the loop should iterate. In each iteration of the loop, it fetches the next element from the array or collection and executes the body of the loop for that element. This continues till all the elements in the collection are exhausted after which the loop is terminated.

Example

The following code demonstrates a basic for-each statement:

int[] input = { 10, 20, 30 };

for (int num : input) {
	System.out.println("Number is " + num);
}

This code first declares an integer array called input. It then uses a for-each loop to iterate through this array. For each iteration, the next value from the array input is fetched and assigned to the variable num. The body of the loop is then executed with this value. The loop is exited once all the elements in the array are exhausted. So, this code produces the following output:

Number is 10
Number is 20
Number is 30

When you want to iterate over an array or a collection a for-each loop is better than a for loop since it automatically fetches the next element and assigns to a variable

Conclusion

Java iteration statements help to repeat a block of code. The while and do-while repeat a block of code as long as a condition is true. The do-while loop should be used when you want the body of the loop to be executed at least once. The for loop is used to iterate over a range of values. The for-each loop is used to iterate over an array or a collection.

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

JAVA TUTORIALS

Recent Posts

RELATED POSTS

Format Decimal Numbers using Strings Within Pattern

As mentioned in earlier posts, the java.text.DecimalFormat class is used to format decimal numbers via predefined patterns specified as String. Apart from the decimal separator,...

How To Create Singleton Class in Java

Design patterns Overview Design patterns are basically solutions to programming problems that developers normally encounter during software development. Design patterns were first documented by four...

Remove Duplicates from List Using HashSet

The Set is also an interface in the 'Java Collection' framework. Unlike a List, a Set does not allow duplicates. Hence you can...

Convert List to Array Using ToArray With Param

There is an overloaded version of the toArray method. This accepts an array as a parameter and returns a result array that is of the same...

Â

CHECKOUT 'HOW-TOs'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string...

MORE ON CODEX

MORE IN THIS CATEGORY

Format Decimal Numbers Using Format Symbols

You can customize which symbols are used as decimal separator, grouping separator, currency seperator etc. using a DecimalFormatSymbols instance together with java.text.DecimalFormat class. The...

Java Tutorial #4 – Control Statements

Introduction Control statements are used to change the flow of execution based on changes to certain variables in the code. One of the types of...

VBS Part 2 – Fundamentals and Concepts

Having gone through the Introductory part, it is time to look at some crucial fundamentals and concepts. This article is to refresh some of...

Desired Capabilities in Selenium Web Driver

1. Desired Capabilities in Selenium The performance of a Web application may vary according to different browsers and operating systems. Hence to ship out a...

OTHER TUTORIALS

Desired Capabilities in Selenium Web Driver

1. Desired Capabilities in Selenium The performance of a Web application may vary according to different browsers and operating systems....
- Advertisement -spot_img