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

Introduction to Apache Maven

1. What is Maven When you write a software application, there are many steps in it like adding the necessary JAR files, compiling the source...

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...

Getting Started With Hibernate

Introduction Hibernate is a framework which allows you to access database tables from Java code. Before Hibernate came into existence, JDBC was widely used. JDBC...

Java Tutorial #2 – Operators in Java

Table of Contents Introduction 1. Assignment Operator 2. Arithmetic Operators 3. Compound Operators 4. Increment & Decrement Operators 5. Relational Operators 6. Logical Operators Introduction Operators are an essential...

Â

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

Java Tutorial #2 – Operators in Java

Table of Contents Introduction 1. Assignment Operator 2. Arithmetic Operators 3. Compound Operators 4. Increment & Decrement Operators 5. Relational Operators 6. Logical Operators Introduction Operators are an essential...

How To Remove Duplicates From List in Java

Introduction A List is an interface in the Java collection framework which can be used to store a group of objects. A List is ordered...

How To Convert List To Array in Java

A common scenario faced by programmers is to convert a Java List to an Array. A 'List' is part of the Collection Framework and...

How To Create Maven Project in Eclipse Without Archetype

Maven is a very popular build and dependency management tool. Eclipse is an IDE that helps developers write and run Java code easily. In...

OTHER TUTORIALS

Getting Started With Atlassian Jira

Jira is one of the best software used for agile development. It is built for a better team contribution...
- Advertisement -spot_img