0Pricing
Java Academy · Lesson

Scope & Lifetime

Understand where variables are visible (scope) and how long they exist (lifetime): blocks, loops, methods, fields, shadowing, and final parameters.

Scope vs lifetime

Scope = where a name (variable) is visible. Lifetime = how long the variable exists. You will see block scope, loop scope, method locals, class fields, and shadowing rules.

Block scope

Block scope: a variable declared inside braces is visible only inside those braces.

public class Main {
  public static void main(String[] args) {
    int a = 10; // visible in main
    {
      int b = 20; // visible only inside this block
      System.out.println("inside block: a=" + a + ", b=" + b);
    }
    System.out.println("outside block: a=" + a);
    // System.out.println(b); // would NOT compile: b is out of scope
  }
}

All lessons in this course

  1. Defining Methods & Parameters
  2. Return Values & Overloading
  3. Scope & Lifetime
← Back to Java Academy