next up previous
Next: Lifetime of local variables Up: Unit 03 Previous: Scope of local variables

Example: scope of local variables

Consider the following program.

public class Visibility {

  public static String duplicate(String s) {
    String t = s + ", " + s;
    return t;
  }

  public static void print1() {
    System.out.println(a);   //ERROR: a is not defined
  }

  public static void print2() {
    System.out.println(t);   //ERROR: t is not defined
  }

  public static void main(String[] args) {
    String a = "Ciao";
    a = duplicate(a);
    print1();
    print2();
    System.out.println(a);
  }
}

During program compilation the compiler will signal two errors:

  1. In the print1 method, the variable a is not visible (since it is defined in the main method).
  2. In the print2 method, the variable t is not visible (since it is defined in the duplicate method).


next up previous
Next: Lifetime of local variables Up: Unit 03 Previous: Scope of local variables