Skip to content

OCP exam prep: variable scope

☕ Java 17 · 🎓 OCP 1Z0-829 · Managing Variable Scope

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.

Four traps to watch for

Trap 1 — The loop counter dies with the loop

A question uses i after for (int i = 0; …) { } and asks if it compiles. It doesn't.

Trap 2 — No redeclaring a name still in scope

Declaring a local in an inner block with the name of an enclosing local doesn't compile, even though the inner one would have a smaller scope.

Trap 3 — Parameters are locals

Method parameters are in scope for the whole method body, and nowhere else.

Trap 4 — var follows the same rules

A var declared in a block goes out of scope when the block ends, like any typed variable.

Practice questions

1. What is the output?

public class Platform {
    public static void main(String[] args) {
        int episodes = 10;
        for (int i = 0; i < 2; i++) {
            int bonus = i * 3;
        }
        System.out.println(episodes);
    }
}

A. 0
B. 10
C. Compilation error: bonus is out of scope
D. Compilation error: episodes is out of scope

Answer

B. episodes is in method scope, so it's available after the loop. bonus is never used outside the loop, so its limited scope causes no error.

2. Which lines, if any, cause a compiler error? (Choose all that apply.)

1: public void playMovie(boolean vip) {
2:     int maxStreams = 3;
3:     if (vip) {
4:         int maxStreams = 5;
5:         System.out.println(maxStreams);
6:     }
7:     System.out.println(maxStreams);
8: }

A. Line 4
B. Line 5
C. Line 7
D. None

Answer

A. maxStreams from line 2 is still in scope inside the if, so line 4 can't declare another one. Lines 5 and 7 are fine on their own.

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