Java conditions, arrays, and loops
Count values that satisfy a boundary condition.
On this page
Variables, main, and basic output.
- Count values that satisfy a boundary condition.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
An enhanced for loop visits each array element. A comparison produces a boolean used by if to decide whether the counter changes.
The >= condition includes a score exactly equal to the pass threshold. The array has a fixed length; the loop reads its elements without changing them.
Code example
class Main {
public static void main(String[] args) {
int[] scores = {49, 50, 80};
int passed = 0;
for (int score : scores) {
if (score >= 50) passed++;
}
System.out.println(passed);
if (passed != 2) throw new AssertionError("count");
}
}2
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
class Main { public static void main(String[] args) { int[] scores = {49, 50, 80}; int passed = 0; for (int score : scores) { if (score >= 50) passed++; } System.out.println(passed); if (passed != 2) throw new AssertionError("count"); }}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create an array of three scores. | scores = [49, 50, 80] | — | |
| Initialize the counter. | passed = 0 | — | |
| 49 fails; 50 passes at the boundary. | passed = 1 | — | |
| 80 also passes. | passed = 2 | — | |
| Print the final count. | passed = 2 | 2 |
Behind the scenes
How Java processes this code
The Java compiler produces bytecode. The JVM loads the class and invokes its main method.
Cost and common mistakes
O(n) time and O(1) auxiliary space.
- Replacing >= with > would exclude score 50.
- Changing the copied loop variable does not change the array's primitive element.
Try it yourself
Add score 0 and score 100.
Reveal answer and reasoning
The count becomes 3 because only 100 adds another passing score.