Java While Loop

The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.

Syntax
snippet
while(condition){
//code to be executed
}
flowchart of java while loop
Example
snippet
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

If you pass true in the while loop, it will be infinitive while loop.

Syntax
snippet
while(true){
//code to be executed
}
Example
snippet
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

Now, you need to press ctrl+c to exit from the program.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +