while loop in java
DevSniper
106 Views
while loop is a fundamental control flow statement of Java. while loop is used to run some block of code several times based on certain condition. It offers a structured and efficient way to handle repetitive tasks.
//initialization while (condition) { // loop body //Increment / decrement }
- condition : It executes before every execution of the loop body. Here we define execution condition of loop body. if the condition is true flow enter inside loop body, After the execution of loop body , the condition is evaluated again until the condition become false. when the condition become false we stop execution of the loop body and terminate loop.
- while loop is used to execute a block of code (loop body) several times.
- while loop is a entry control loop it verifies condition before executing of the loop body.
- while loop simplifies repetitive tasks.
- It is useful where we need to repeat an operation until a certain condition is evaluated to be true.
- Simple while loop
- Nested while loop
- Infinite while loop
Simple while loop
public class RebootMemory { public static void main(String[] args) { //initialization int i=3; while(i<10) // condition/expression { System.out.print(i+" "); // Increment i++; } } }
3 4 5 6 7 8 9
Nested while loop
if we place one while loop inside another loop this is called nested while loop. inner while loop execute completely for every outer loop execution. outer loop can be for loop , while loop or do while loop.
public class RebootMemory { public static void main(String[] args) { for( int i=1 ; i<=2; i++ ) { System.out.println("Inside Outer loop i : "+i); int j=1; while(j<=3) { System.out.println("=> inside inner loop i :- "+i+" and j : "+j); j++; } } } }
Inside Outer loop i : 1 => inside inner loop i :- 1 and j : 1 => inside inner loop i :- 1 and j : 2 => inside inner loop i :- 1 and j : 3 Inside Outer loop i : 2 => inside inner loop i :- 2 and j : 1 => inside inner loop i :- 2 and j : 2 => inside inner loop i :- 2 and j : 3
Infinite while loop
if we define a condition that never becomes false, loop become Infinite Loop.
while( true) { // loop body }
while(2<5) { // loop body }
int i=5; while(i<10) { System.out.println(i); }