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 Locale

If you want to create a DecimalFormat instance for a specific Locale, create a NumberFormat and cast it to a DecimalFormat. The java.text.DecimalFormat class is...

Format Decimal Numbers with Grouping Separator

The DecimalFormat class has a method called setGroupingSize() which sets how many digits of the integer part to group. Groups are separated by the...

Rounding Decimal Number With Java DecimalFormat

The DecimalFormat class has a method called setRoundingMode() which can be used for setting the rounding mode for DecimalFormat object. The setRoundingMode() accepts RoundingMode...

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

Remove Duplicates from List Using For-Loop

The simplest way to remove duplicates from a 'List' is to use a for-loop. The following code snippet demonstrates this method. First, the code creates...

Setting Max/Min Digits For Decimal Numbers With Java DecimalFormat

The DecimalFormat class offers the following four such methods which can be used to easily set the maximum and/or minimum digits for decimal numbers....

Remove Duplicates from List Using Stream

Java 8 has added the Stream API that helps to easily perform bulk operations on Collections. A new method called stream() method has been...

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

Essentials of Typical QTP/UFT Framework

Table of Contents Essentials 1: Test Artefacts Repository Essentials 2: Error Handling and Recovery Essentials 3: Object Identification Method Essentials 4: Test...
- Advertisement -spot_img