Scope and Lifetime of Variables

Variables declared inside a scope are not accessible to code outside.
Scopes can be nested. The outer scope encloses the inner scope.
Variables declared in the outer scope are visible to the inner scope.
Variables declared in the inner scope are not visible to the outside scope.

public class Main {
  public static void main(String args[]) {
    int x; // known within main
    x = 10;
    if (x == 10) { // start new scope
      int y = 20; // y is known only to this block
      // x and y both known here.
      System.out.println("x and y: " + x + " " + y);
      x = y + 2;
    }
    System.out.println("x is " + x);
  }
}

The output:


x and y: 10 20
x is 22

In the following code, y is defined inside if statement and it is not accessible outside if statement.


public class Main {
  public static void main(String args[]) {
    if (true) { // start new scope
      int y = 20; // known only to this block
      System.out.println("y: " + y);

    }
    y = 100; // Error! y not known here
  }
}

It generates the following error message:


D:\>javac Main.java
Main.java:9: cannot find symbol
symbol  : variable y
location: class Main
    y = 100; // Error! y not known here
    ^
1 error

Variables declared within a scope will not hold their values between calls to that scope.

  

public class Main {
  public static void main(String args[]) {
    for (int i = 0; i < 3; i++) {
      int y = 0; // y is initialized each time block is entered
      System.out.println("y is: " + y); 
      y = 100;
      System.out.println("y is now: " + y);

    }
  }
}

The output generated by this program is shown here:


y is: 0
y is now: 100
y is: 0
y is now: 100
y is: 0
y is now: 100

A variable in the inner scope cannot have the same name as one variable in an outer scope.


public class Main {

  public static void main(String args[]) {
    int i = 1;
    { // creates a new scope

      int i = 2; // Compile-time error
    }
  }
}

If you try to compile the code above, compiler will generate the following error message.


D:\>javac Main.java
Main.java:7: i is already defined in main(java.lang.String[])
      int i = 2; // Compile-time error
          ^
1 error
Home 
  Java Book 
    Language Basics  

Variables:
  1. Variable stores value in a Java program
  2. Assignment Operator
  3. Dynamic Initialization
  4. Scope and Lifetime of Variables