Before this lesson

Be able to compile and run Main.java with the JDK. Understand variables and output statements.

What you will be able to do

Recognize integer division, string comparison and loop boundaries.

Understand the mechanism

int fits the small integers here. With two integer operands, 5/2 is 2. Convert an operand to double before division to preserve a fraction; converting the result afterwards cannot restore it.

Compare string contents with equals. == compares object identity, so constant reuse can produce misleading results. "Java".equals(value) also handles null safely.

Reject invalid scores before accumulating. continue skips only the current iteration. An average must also handle zero valid records.

Runnable example

Use JDK 21. Save Main.java in a separate practice directory, compile with javac -encoding UTF-8 Main.java, then run java Main. Each lesson is independent; do not combine multiple public Main classes.


public class Main {
    public static void main(String[] args) {
        int[] scores = {60, 90, -1, 100};
        int sum = 0, count = 0;
        for (int score : scores) {
            if (score < 0 || score > 100) continue;
            sum += score;
            count++;
        }
        System.out.println(5 / 2);
        System.out.println((double) 5 / 2);
        System.out.println("Java".equals(new String("Java")));
        System.out.println(count == 0 ? "no scores" : "sum=" + sum);
    }
}

Trace and verify

Valid scores are 60, 90 and 100, totaling 250. The -1 is skipped. The first two lines are 2 and 2.5.

Common mistakes and boundaries

Integers can overflow; this small example is not a large-scale statistics solution. Array indices range from zero through length-1.

Practice challenge

Compute the valid average and test an empty array.

Reference solution and reasoning

Check count==0 first; otherwise use (double)sum/count. This sample is approximately 83.333. An empty array reports no scores instead of dividing by zero.

Further reading