Skip to content

OCP exam prep: initializing variables

☕ Java 17 · 🎓 OCP 1Z0-829 · Giving Variables Their First Value

Optional page

This page is for readers preparing the Oracle Certified Professional Java SE 17 Developer exam (1Z0-829). The concepts are all you need otherwise.

Three traps to watch for

Trap 1 — Reading a local before assigning it

int score; System.out.println(score); doesn't compile. The compiler never picks a default for a local.

Trap 2 — An unassigned final field

final int maxStreams; with no assignment in a field initializer, an initializer block or every constructor: compiler error, reported on the field declaration.

Trap 3 — Assigned on only some paths

int views; if (c) views = 5; System.out.println(views); doesn't compile: might not have been initialized. Every path must assign it.

Practice questions

1. What is the output?

public class Movie {
    int views;
    public static void main(String[] args) {
        Movie m = new Movie();
        System.out.println(m.views);
    }
}

A. Compilation error
B. Runtime exception
C. 0
D. null

Answer

C. views is an int field, so it defaults to 0. null is the default for object types only.

2. Where does this class fail to compile? (Choose all that apply.)

public class Subscription {
    final int maxScreens;                 // Line 1
    String plan;
    public void checkPlan() {
        String msg;
        System.out.println(msg);          // Line A
        System.out.println(plan);         // Line B
        System.out.println(maxScreens);   // Line C
    }
}

A. Line 1
B. Line A
C. Line B
D. Line C

Answer

A and B. Line A reads a local that was never assigned. maxScreens is final and never assigned, and javac reports that on its declaration (Line 1), not where it's read. Line B is fine: plan defaults to null. Line C has no error of its own.

← Back to the series · All 1Z0-829 pages