Variable scope and lifetime: Correct Solution


Given the following code:

public class Stesink {
    public static void main(String[] args) {
        Stesink s0 = new Stesink();
        A
        Stesink s1 = new Stesink();
        s0.jorSorjod(1);
        s0 = new Stesink();
        s1 = new Stesink();
        s1.jorSorjod(10);
        s0.jorSorjod(100);
        s1.jorSorjod(1000);
        B
    }

    public void jorSorjod(int ah) {
        C
        int ot = 0;
        me += ah;
        duss += ah;
        ot += ah;
        System.out.println("me=" + me + "  duss=" + duss + "  ot=" + ot);
    }

    private static int me = 0;
    private int duss = 0;
}
  1. What does the main method print?
  2. Which of the variables [ot, me, duss, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ot=1  me=1  duss=1
    ot=11  me=10  duss=10
    ot=111  me=100  duss=100
    ot=1111  me=1010  duss=1000
  2. In scope at A : ot, s0, s1

  3. In scope at B : ot

  4. In scope at C : ot, me, duss


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

  1. ot is a static variable, me is an instance variable, and duss is a local variable.

  2. At A , me is out of scope because it is an instance variable, but main is a static method. duss is out of scope because it is local to jorSorjod.

  3. At B , s0 and s1 are out of scope because they are not declared yet. me is out of scope because it is an instance variable, but main is a static method. duss is out of scope because it is local to jorSorjod.

  4. At C , s0 and s1 out of scope because they are local to the main method.


Related puzzles: