Unit 1 · Lesson 415 minAcademic review pending

The same array, minus the danger

Control statements are nearly identical to C. Arrays are the interesting change: a Java array knows its own length and cannot be walked past its end by accident — the two habits that caused the most bugs in CS105ES.

Choose explanation

After this lesson

You should be able to

  • Declare and use a Java array, and explain why array.length exists.
  • Use if, while, for, and switch in Java, noticing what is identical to C and what is not.
  • Explain the difference between implicit widening and explicit casting.
01

Control statements: almost nothing to relearn

if, else, while, for, and switch in Java look and behave exactly like C. The one real difference is the condition itself: C accepted any number as a condition, where non-zero meant true. Java requires an actual boolean expression — if (marks) does not even compile in Java, because marks is an int, not a boolean. That removes the entire class of accidental if (x = 5) bugs you met in CS105ES, because an assignment expression's value is not a boolean either.

This is a direct, deliberate consequence of Java making boolean a real, separate type. Where C let a mistake compile silently, Java's stricter typing turns the same mistake into a compiler error you see immediately — the language enforcing a discipline that in C you had to enforce on yourself.

A bug C allows, that Java refuses to compile
int marks = 87;

// C: this compiles and is almost always a bug
// if (marks = 90) { ... }

// Java: this line does not compile at all
// if (marks) { ... }          // error: incompatible types

if (marks >= 35) {
    System.out.println("Pass");
}
02

Arrays that know their own size

In C, an array is just a pointer to the first element — the array itself carries no record of how many elements it has. You had to pass the size separately to every function that used it, and reading past the end silently returned garbage memory instead of an error. A Java array is an actual object: it always knows its own length, accessible as array.length, no separate variable required.

Reading or writing past the last valid index in Java throws an ArrayIndexOutOfBoundsException immediately, at the exact line where the mistake happened, instead of silently corrupting nearby memory the way an off-by-one error could in a CS105ES array program. The enhanced for loop, for (int value : marks), also removes the index entirely when you only need to visit every element, not their positions.

Length, bounds checking, and a loop with no index
int[] marks = {78, 81, 90, 65, 88};

System.out.println(marks.length);   // 5, no separate variable needed

for (int value : marks) {           // no index at all
    System.out.println(value);
}

// marks[10];  // throws ArrayIndexOutOfBoundsException at this exact line
03

Widening happens for free, narrowing needs your permission

The int-to-double promotion you relied on in CS105ES division still works the same way in Java, and this direction — a smaller type fitting safely into a larger one — happens automatically, called widening. int to long, int to double, and char to int all happen without you writing anything extra, because no information can be lost going that direction.

The reverse — narrowing, like double to int — needs an explicit cast, exactly like the (double) total cast from CS105ES, except now the compiler insists on it rather than merely allowing it. Without the cast, double result = 7 / 2; behaves exactly as it did in C — integer division truncates first — but int result = 7.5; will not even compile, because Java refuses to silently discard the fractional part unless you explicitly say that is what you want.

Try it yourself

Write a Java program with an array of five exam scores. Using an enhanced for loop, print each score, and separately compute and print the average as a double, casting correctly so the division is not truncated.

Need a hint?

Summing the array still needs a normal for loop or a running total, since you need the count too — the enhanced for loop is only for reading values, not counting them.

Check the worked solution

The enhanced for loop cleanly handles printing every value, but computing the average still needs an index-based loop or a running sum, because you need to divide by the count at the end — exactly the accumulator pattern from CS105ES, just written in Java syntax. The cast to double before dividing is required for the same reason it was in C: integer division would silently truncate otherwise.

public class ScoreDemo {
    public static void main(String[] args) {
        int[] scores = {78, 81, 90, 65, 88};
        int sum = 0;

        for (int score : scores) {
            System.out.println(score);
            sum = sum + score;
        }

        double average = (double) sum / scores.length;
        System.out.println("Average: " + average);
    }
}

Quick check

Why does int result = 7.5; fail to compile in Java, when double result = 7; compiles fine?

Select an answer to check your thinking.

Why this lesson exists

Syllabus mapping

Arrays, operators, expressions, control statements, type conversion and casting.

Maps to course outcome CO1.