← Back to Chapters

Variable Scope & Lifetime in Java

? Variable Scope & Lifetime in Java

? Quick Overview

In Java, scope defines where a variable can be accessed, while lifetime defines how long the variable exists in memory. Understanding both is essential for writing clean, efficient, and bug-free programs.

? Key Concepts

  • Scope controls visibility of variables
  • Lifetime controls existence in memory
  • Java has local, instance, and static variables
  • Memory allocation depends on variable type

? Syntax & Theory

  • Local Variables → Declared inside methods or blocks (Stack Memory)
  • Instance Variables → Declared inside class, outside methods (Heap Memory)
  • Static Variables → Declared with static keyword (Static/Metaspace Memory)

? Code Examples

? View Code Example
// Demonstrating variable scope and lifetime
class ScopeDemo {
  
  // 1. Static Variable (Class Scope)
  static int staticVar = 20;

  // 2. Instance Variable (Object Scope)
  int instanceVar = 10;

  void showScope() {
    // 3. Local Variable (Method Scope)
    int localVar = 30;
    
    System.out.println(localVar);
    System.out.println(instanceVar);
    System.out.println(staticVar);
  }
}

? Live Output / Explanation

Explanation

  • localVar exists only inside showScope()
  • instanceVar exists as long as object exists
  • staticVar exists until program ends

?️ Interactive Scope Visualizer

Click the buttons to control the program flow and watch how memory changes.

Static Memory

staticVar 20

Heap (Objects)

Empty

Stack (Methods)

Empty

✅ Tips & Best Practices

  • Keep variable scope as small as possible
  • Avoid unnecessary global/static variables
  • Use meaningful variable names

? Try It Yourself

  • Create a class with local, instance, and static variables
  • Print values from different methods
  • Observe access restrictions