Java · Course navigation

Java conditions, arrays, and loops

Count values that satisfy a boundary condition.

On this page
Before you start

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

Java
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");
    }
}
Output
2

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1class Main {
2 public static void main(String[] args) {
3 int[] scores = {49, 50, 80};
4 int passed = 0;
5 for (int score : scores) {
6 if (score >= 50) passed++;
7 }
8 System.out.println(passed);
9 if (passed != 2) throw new AssertionError("count");
10 }
11}

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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading