Variable scope and lifetime: Correct Solution


Given the following code:

public class Sniseil {
    private static int essa = 0;
    private int ost = 0;

    public void rocsen(int bri) {
        int zeen = 0;
        A
        ost += bri;
        zeen += bri;
        essa += bri;
        System.out.println("ost=" + ost + "  zeen=" + zeen + "  essa=" + essa);
    }

    public static void main(String[] args) {
        B
        Sniseil s0 = new Sniseil();
        Sniseil s1 = new Sniseil();
        C
        s0.rocsen(1);
        s1.rocsen(10);
        s1 = new Sniseil();
        s0.rocsen(100);
        s0 = new Sniseil();
        s1.rocsen(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [essa, ost, zeen, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    essa=1  ost=1  zeen=1
    essa=10  ost=10  zeen=11
    essa=101  ost=100  zeen=111
    essa=1000  ost=1000  zeen=1111
  2. In scope at A : zeen, essa, ost

  3. In scope at B : zeen, s0

  4. In scope at C : zeen, s0, s1


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

  1. zeen is a static variable, essa is an instance variable, and ost is a local variable.

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

  3. At B , s1 is out of scope because it is not declared yet. essa is out of scope because it is an instance variable, but main is a static method. ost is out of scope because it is local to rocsen.

  4. At C , essa is out of scope because it is an instance variable, but main is a static method. ost is out of scope because it is local to rocsen.


Related puzzles: