Conditions and loops
Decide which blocks run and trace how a Java loop advances its counter.
int count = 0;while (count < limit) { count += 1;}System.out.println(count);Set count to zero before checking the loop condition.
Read the Boolean expression
Java requires a boolean expression inside the parentheses after if or while. Numeric comparison operators include <, <=, and ==. Combine Boolean expressions with && and ||.
How it works
Trace the order of a loop’s operations: setup, condition, body, then update. After the update the condition is checked again. If it fails on the first check, the body never runs. A counter table helps you see exactly which values passed the check.
Walk through the loop condition
A while loop checks the condition before each body execution. The diagram and example start at zero and update by one while count < limit. When count reaches the limit, the next check is false. You can also express this pattern with a for loop using an initializer, a condition and an update.
Code example
public class Main {
public static void main(String[] args) {
int count = 0;
int limit = 5;
while (count < limit) {
count++;
System.out.println(count);
}
}
}Check your understanding
Add only the even numbers from 1 through the input limit, inclusive.
See the example and explanation
- Example 1
- Given
6 - Answer
12 - Example 2
- Given
1 - Answer
0
The loop checks number % 2 == 0 before adding. For the limit 6, the qualifying values are 2, 4, and 6, which add to 12.