Java While Loop - Javatpoint
Java While Loop - Javatpoint
https://www.javatpoint.com/java-while-loop 1/10
5/18/22, 2:36 PM Java while loop - Javatpoint
The while loop is considered as a repeating if statement. If the number of iteration is not fixed, it is
recommended to use the while loop.
Syntax:
while (condition){
//code to be executed
I ncrement / decrement statement
}
1. Condition: It is an expression which is tested. If the condition is true, the loop body is executed
and control goes to update expression. When the condition becomes false, we exit the while loop.
Example:
i <=100
2. Update expression: Every time the loop body is executed, this expression increments or
decrements loop variable.
https://www.javatpoint.com/java-while-loop 2/10
5/18/22, 2:36 PM Java while loop - Javatpoint
Example:
i++;
Here, the important thing about while loop is that, sometimes it may not even execute. If the
condition to be tested results into false, the loop body is skipped and first statement after the while
loop will be executed.
Example:
https://www.javatpoint.com/java-while-loop 3/10
5/18/22, 2:36 PM Java while loop - Javatpoint
In the below example, we print integer values from 1 to 10. Unlike the for loop, we separately need
to initialize and increment the variable used in the condition (here, i). Otherwise, the loop will
execute infinitely.
WhileExample.java
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
}
}
Test it Now
Output:
10
https://www.javatpoint.com/java-while-loop 4/10
5/18/22, 2:36 PM Java while loop - Javatpoint
Syntax:
while(true){
//code to be executed
}
Example:
WhileExample2.java
public class WhileExample2 {
public static void main(String[] args) {
// setting the infinite while loop by passing true to the condition
while(true){
System.out.println("infinitive while loop");
}
}
}
Output:
https://www.javatpoint.com/java-while-loop 5/10
5/18/22, 2:36 PM Java while loop - Javatpoint
ctrl+c
In the above code, we need to enter Ctrl + C command to terminate the infinite loop.
← Prev
Next →
Youtube
For Videos Join Our Youtube Channel: Join Now
Feedback
https://www.javatpoint.com/java-while-loop 6/10
5/18/22, 2:36 PM Java while loop - Javatpoint
Preparation
https://www.javatpoint.com/java-while-loop 7/10
5/18/22, 2:36 PM Java while loop - Javatpoint
Company
Interview
Questions
Company Questions
Trending Technologies
https://www.javatpoint.com/java-while-loop 8/10
5/18/22, 2:36 PM Java while loop - Javatpoint
B.Tech / MCA
https://www.javatpoint.com/java-while-loop 9/10
5/18/22, 2:36 PM Java while loop - Javatpoint
https://www.javatpoint.com/java-while-loop 10/10