Java While Loop

By | September 29, 2021

Unlike for-loop, while loop is used when the number of iteration is not known. The while loop will execute the program several times until the condition is false.

Syntax

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

Example

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

Output

1
2
3

Infinitive while loop

The while loop will execute infinite time when we pass the true value as the condition. If you want to exit from the infinite loop then press ctrl+c.

Syntax

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

Example

Vamware
public class WhileExample2 {  
public static void main(String[] args) {  
    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

People are also reading:

Leave a Reply

Your email address will not be published. Required fields are marked *