A Java while loop tests its condition before each iteration. If the initial condition is false, the body never runs.
A simple example
Print while the number is at most 3
Start withn starts at 1
Do thisPrint n, add 1
ResultStop at 4
The test happens before each print. It succeeds for 1, 2 and 3. At 4 it fails, so 4 is never printed.Main.java
class Main {
public static void main(String[] args) throws Exception {
int n = 1;
while (n <= 3) {
System.out.println(n);
n++;
}
}
}
Output
1
2
3
Fill complete snack bags
The canteen has 17 apples and packs five in each bag. Check the remaining pile before filling each bag. Three full bags leave two apples for the next delivery.
Example: #1 - Simple while Loop
Print the integers from 1 through 5.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int counter = 1;
while(counter <= 5) {
System.out.println(counter);
// Increment the number by 1 using Post Increment
counter++;
}
}
}
Output
1
2
3
4
5
Advertisements
Example: #2 - while Loop (un-reached code)
Trace the initial counter and check the condition before the first iteration.
With a starting value of 10, the test for a counter no greater than 5 is false.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int counter = 10;
System.out.println("Execution before while loop");
while(counter <= 5) {
System.out.println(counter);
// Increment the number by 1 using Post Increment
counter++;
}
System.out.println("Execution after while loop");
}
}
Output
Execution before while loop
Execution after while loop
Example: #3 - while Loop (Infinite loop)
The counter never changes in this example, so the loop runs indefinitely.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int counter = 1;
while(counter <= 5) {
System.out.println(counter);
}
}
}
Output
1
1
1
.
.
1
Java while Loop with break Statement
A break exits the loop immediately.
Example: #4 - while Loop with break Statement
Stop after printing 3.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int counter = 1;
while(counter <= 5) {
System.out.println(counter);
// Terminate the execution once counter reached 3
if(counter == 3) {
break;
}
// Increment the number by 1 using Post Increment
counter++;
}
}
}
Output
1
2
3
Java while Loop with continue Statement
A continue skips the rest of the current iteration and reaches the next loop test.
Example: #5 - while Loop with continue Statement
Skip the iteration for the counter value 3.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int counter = 0;
while(counter <= 5) {
// Increment the number by 1 using Post Increment
counter++;
// skips the iteration once counter reached 3
if(counter == 3) {
continue;
}
System.out.println(counter);
}
}
}