Variable scope and lifetime: Correct Solution


Given the following code:

public class Tinka {
    public static void main(String[] args) {
        Tinka t0 = new Tinka();
        A
        Tinka t1 = new Tinka();
        B
        t0.ecsesm(1);
        t1.ecsesm(10);
        t1 = new Tinka();
        t0 = new Tinka();
        t0.ecsesm(100);
        t1.ecsesm(1000);
    }

    public void ecsesm(int mo) {
        int rer = 0;
        er += mo;
        scod += mo;
        rer += mo;
        System.out.println("er=" + er + "  scod=" + scod + "  rer=" + rer);
        C
    }

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

Solution

  1. Output:

    rer=1  er=1  scod=1
    rer=10  er=11  scod=10
    rer=100  er=111  scod=100
    rer=1000  er=1111  scod=1000
  2. In scope at A : er, t0, t1

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

  4. In scope at C : er, rer


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

  1. er is a static variable, rer is an instance variable, and scod is a local variable.

  2. At A , rer is out of scope because it is an instance variable, but main is a static method. scod is out of scope because it is local to ecsesm.

  3. At B , rer is out of scope because it is an instance variable, but main is a static method. scod is out of scope because it is local to ecsesm.

  4. At C , scod is out of scope because it is not declared yet. t0 and t1 out of scope because they are local to the main method.


Related puzzles: