Do While Loop in Java

The do-while loop in Java is a construct that allows a certain part of the program to be repeated until a specified condition becomes true. It is particularly useful when the number of iterations is not predetermined and you need to ensure that the loop is executed at least once.

The key characteristic of the Java do-while loop is that it is an exit control loop. This means that unlike the while loop and for loop, the condition is checked at the end of the loop body. Consequently, the do-while loop guarantees that the loop body will be executed at least once, regardless of the condition’s initial value.

Syntax:

do{    
//code to be executed / loop body  
//update statement   
}while (condition);

Different parts present in the do-while loop:

Condition: In a do-while loop, the condition is an expression that is evaluated. If the condition evaluates to true, the loop body is executed, and control then moves to update the expression. This process continues until the condition eventually becomes false, at which point the loop automatically terminates.

Example:

i <=1000

Update expression: In a do-while loop, the update expression is responsible for modifying the loop variable after each iteration of the loop body.

Example:

i++;

Flowchart of a do-while loop:

Example:

Consider the following example where we aim to print integer values from 1 to 15. In this specific case, it is important to note that, unlike the for loop, the initialization and incrementation of the variable used in the condition (in this case, i) must be handled separately. Failing to do so could lead to an infinite loop.

DoWhileExample.java

public class DoWhileExample {    
public static void main(String[] args) {    
    int i=1;    
    do{    
        System.out.println(i);    
    i++;    
    }while(i<=15);    
}    
}

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Infinitive do-while Loop in Java:

If the condition passed in a do-while loop is always true, it will result in an infinite do-while loop.

Syntax:

do{  
//code to be executed  
}while(true);

Example:

DoWhileExample1.java

public class DoWhileExample1 {  
public static void main(String[] args) {  
    do{  
        System.out.println("infinitive do while loop");  
    }while(true);  
}  
}

Output:

infinitive do while loop
infinitive do while loop
infinitive do while loop
ctrl+c

we need to enter Ctrl + C command to terminate the infinite loop.

For comprehensive insights into the Do While Loop in Java, we encourage you to follow tutorials.freshersnow.com regularly.