Variable scope and lifetime: Correct Solution


Given the following code:

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

    private int ne = 0;

    public void cemDidla(int me) {
        int zec = 0;
        ukur += me;
        ne += me;
        zec += me;
        System.out.println("ukur=" + ukur + "  ne=" + ne + "  zec=" + zec);
        C
    }

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

Solution

  1. Output:

    zec=1  ukur=1  ne=1
    zec=11  ukur=10  ne=10
    zec=111  ukur=101  ne=100
    zec=1111  ukur=1101  ne=1000
  2. In scope at A : zec, s0

  3. In scope at B : zec, s0, s1

  4. In scope at C : zec, ukur


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

  1. zec is a static variable, ukur is an instance variable, and ne is a local variable.

  2. At A , s1 is out of scope because it is not declared yet. ukur is out of scope because it is an instance variable, but main is a static method. ne is out of scope because it is local to cemDidla.

  3. At B , ukur is out of scope because it is an instance variable, but main is a static method. ne is out of scope because it is local to cemDidla.

  4. At C , ne is out of scope because it is not declared yet. s0 and s1 out of scope because they are local to the main method.


Related puzzles: