Unlike for-loop , the while loop is used when the number of iterations is unknown. The while loop will execute a 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, press ctrl+c .
Syntax
while(true){
//code to be executed
}
Example
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