While Loop in Java

The Java while loop is a control flow statement that repeatedly executes a block of code as long as a specified boolean condition is true. It serves as a repeating if statement, allowing the program to iterate a section of code multiple times until the condition evaluates to false. The while loop is particularly useful when the number of iterations is not predetermined and may vary during runtime. It provides flexibility for creating dynamic looping structures.

Syntax:

while (condition){    
//code to be executed   
increment / decrement statement  
}

The different parts of the do-while loop:

Condition: The condition in a Java while loop is an expression that is evaluated before each iteration. If the condition evaluates to true, the loop body is executed, and then the control proceeds to update the expression. This process continues as long as the condition remains true. Once the condition evaluates to false, the program exits the while loop and continues with the next line of code following the loop.

Example:

i <=100

Update expression: During each iteration of a Java while loop, the loop variable is typically incremented or decremented within the loop body. This expression modifies the value of the loop variable, allowing for the progression or regression of the loop. By updating the loop variable, we control the flow and progression of the loop. The modification of the loop variable ensures that the loop continues to execute until the condition evaluates to false, or until the desired number of iterations is reached.

Example:

i++;

While Loop flowchart in Java:

Example:

WhileExample.java

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

Output:

1
2
3
4
5
6
7
8
9
10

Infinitive While Loop in Java:

By providing the boolean value true as the condition in a Java while loop, we create an infinite loop. An infinite while loop will continue executing indefinitely until a break statement or some other control flow mechanism is used to exit the loop.

Syntax:

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

Example:

WhileExample2.java

public class WhileExample2 {    
public static void main(String[] args) {   
 // setting the infinite while loop by passing true to the condition  
    while(true){    
        System.out.println("infinitive while loop");    
    }    
}    
}

Output:

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

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

To delve deeper into the understanding of the While Loop in Java, please consider following tutorials.freshersnow.com.