Variable scope and lifetime: Correct Solution


Given the following code:

public class Triseng {
    private static int scro = 0;

    public void tatch(int in) {
        int hea = 0;
        A
        scro += in;
        voed += in;
        hea += in;
        System.out.println("scro=" + scro + "  voed=" + voed + "  hea=" + hea);
    }

    public static void main(String[] args) {
        Triseng t0 = new Triseng();
        B
        Triseng t1 = new Triseng();
        t0.tatch(1);
        t1.tatch(10);
        t0 = new Triseng();
        t0.tatch(100);
        t1 = new Triseng();
        t1.tatch(1000);
        C
    }

    private int voed = 0;
}
  1. What does the main method print?
  2. Which of the variables [hea, scro, voed, t0, t1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    hea=1  scro=1  voed=1
    hea=11  scro=10  voed=10
    hea=111  scro=100  voed=100
    hea=1111  scro=1000  voed=1000
  2. In scope at A : hea, scro, voed

  3. In scope at B : hea, t0, t1

  4. In scope at C : hea


Explanation (which you do not need to write out in your submitted solution):

  1. hea is a static variable, scro is an instance variable, and voed is a local variable.

  2. At A , t0 and t1 out of scope because they are local to the main method.

  3. At B , scro is out of scope because it is an instance variable, but main is a static method. voed is out of scope because it is local to tatch.

  4. At C , t0 and t1 are out of scope because they are not declared yet. scro is out of scope because it is an instance variable, but main is a static method. voed is out of scope because it is local to tatch.


Related puzzles: