Skip to content

Lab: three levels of scope

☕ Java 17 · Managing Variable Scope · 3/3

Goal: build a watch session that uses field scope, method scope and loop scope in one class, and see what each variable can reach.

Setup: create com/netflix/model/User.java under your source folder.

Step 1 — A field

package com.netflix.model;

class User {
    String username;
}

Declared in the class body, username is reachable from every method of User.

Step 2 — A method-level variable

    public void watchContent(boolean premium) {
        int streamsLeft = premium ? 4 : 1;
    }

streamsLeft is declared at the top of the method, outside any block: it lives until the method ends. (premium ? 4 : 1 gives 4 if premium is true, 1 otherwise.)

Step 3 — Loop-scoped variables

Inside watchContent, after streamsLeft:

        for (int i = 0; i < streamsLeft; i++) {
            var content = fetchNext();
            play(content);
        } // content and i are gone here

        // streamsLeft is still alive
        logSession(username, streamsLeft);

i and content disappear when the loop ends. streamsLeft and the field username are still in scope for logSession. Declare streamsLeft inside the loop instead, and the last line no longer compiles.

Step 4 — Helper methods and main

    String fetchNext() {
        return "Stranger Things S01E01";
    }

    void play(String content) {
        System.out.println("  Playing: " + content);
    }

    void logSession(String user, int streams) {
        System.out.println("Session logged for: " + user + " | Streams allowed: " + streams);
    }

    public static void main(String[] args) {
        User user = new User();
        user.username = "mounir_netflix";
        System.out.println("--- Starting watch session ---");
        user.watchContent(true);
        System.out.println("--- Session complete ---");
    }

Step 5 — Run

$ javac com/netflix/model/User.java
$ java com.netflix.model.User
--- Starting watch session ---
  Playing: Stranger Things S01E01
  Playing: Stranger Things S01E01
  Playing: Stranger Things S01E01
  Playing: Stranger Things S01E01
Session logged for: mounir_netflix | Streams allowed: 4
--- Session complete ---

A premium user gets 4 streams, so the loop runs 4 times. After it, the method still reaches streamsLeft and the field username.

Full code on GitHub

← Loops and tracing · Back to the series


🎓 Preparing the OCP Java 17 exam? Exam traps and practice questions for this section → (optional)