In this tutorial, we are going to learn how to use while loop in Java. I hope you have read Java For-Loop Statement.
In Java, looping statements are used to execute instructions repeatedly when your program meets a certain condition or evaluates to true.
1. Java While Loop Statement:
Java While Loop is used to iterate part of a program repeatedly when the number of iteration is not fixed.
Syntax:
while(condition){
//code to be executed
}
Example:
public class DemoClass {
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
2. Java Do-While Loop Statement:
Java do-while loop is very similar to simple while loop in Java. But the only difference is “if you want to make a program run at least once” then using do-while loop in Java is recommended.
Syntax:
do{
//code to be executed
}
while(condition);
Example:
public class DemoClass {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
Output:
1
2
3
4
5
3. Frequently Asked Questions:
Can we have infinite while loop?
Yes, we can have an infinite while and do-while loop statement in Java. See below example:
public class DemoClass {
public static void main(String[] args) {
while (true) {
System.out.println("This is an infinite loop");
}
}
}
Output:
This is an infinite loop
This is an infinite loop
This is an infinite loop
This is an infinite loop
This is an infinite loop
This is an infinite loop
//need to manually terminate
I hope you’ve understood while loop statement in java