OCP exam prep: declaring variables¶
☕ Java 17 · 🎓 OCP 1Z0-829 · Declaring Variables
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.
Exam objective: Understand variable scopes, use local variable type inference, and make objects immutable.
Four traps to watch for¶
Trap 1 — var is not a reserved word
var is a reserved type name, not a keyword. var var = 5; compiles, and so does a method named var. But a class, interface or other type can't be named var.
Trap 2 — No compound var declarations
var a = 1, b = 2; doesn't compile. One variable per var statement.
Trap 3 — Uninitialized locals
int x; System.out.println(x); doesn't compile. Fields get defaults; local variables don't.
Trap 4 — final locks the reference, not the object
final String[] titles = new String[3]; titles[0] = "Dune"; compiles. Only titles = … is forbidden.
Practice questions¶
1. Inside a method, which line compiles?
A. var genre;
B. var title = "Oppenheimer";
C. var season = 1, episode = 3;
D. var rating = null;
Answer
B. A has no value to infer from, C declares two variables with one var, and D gives null, which has no type. Only B lets the compiler infer String.
2. What is the output?
public class StreamingApp {
public static void main(String[] args) {
final int MAX_STREAMS = 5;
int current = MAX_STREAMS;
current = 3;
System.out.println(current + " / " + MAX_STREAMS);
}
}
A. 5 / 5
B. 3 / 5
C. Compilation error
D. 3 / 3
Answer
B. current starts with a copy of 5, then is reassigned to 3. That's allowed: current isn't final. MAX_STREAMS is never reassigned and stays 5.