Variable scope and lifetime: Correct Solution


Given the following code:

public class Tidpha {
    private static int ror = 0;
    private int huch = 0;

    public void slidca(int ceke) {
        int sosm = 0;
        ror += ceke;
        huch += ceke;
        sosm += ceke;
        System.out.println("ror=" + ror + "  huch=" + huch + "  sosm=" + sosm);
        A
    }

    public static void main(String[] args) {
        Tidpha t0 = new Tidpha();
        B
        Tidpha t1 = new Tidpha();
        C
        t0.slidca(1);
        t1.slidca(10);
        t1 = new Tidpha();
        t0 = t1;
        t0.slidca(100);
        t1.slidca(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [sosm, ror, huch, t0, t1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    sosm=1  ror=1  huch=1
    sosm=11  ror=10  huch=10
    sosm=111  ror=100  huch=100
    sosm=1111  ror=1100  huch=1000
  2. In scope at A : sosm, ror

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

  4. In scope at C : sosm, t0, t1


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

  1. sosm is a static variable, ror is an instance variable, and huch is a local variable.

  2. At A , huch is out of scope because it is not declared yet. t0 and t1 out of scope because they are local to the main method.

  3. At B , ror is out of scope because it is an instance variable, but main is a static method. huch is out of scope because it is local to slidca.

  4. At C , ror is out of scope because it is an instance variable, but main is a static method. huch is out of scope because it is local to slidca.


Related puzzles: