Variable scope and lifetime: Correct Solution


Given the following code:

public class Sphiu {
    private static int id = 0;

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

    public void bisqa(int ias) {
        int cae = 0;
        girm += ias;
        cae += ias;
        id += ias;
        System.out.println("girm=" + girm + "  cae=" + cae + "  id=" + id);
        C
    }

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

Solution

  1. Output:

    id=1  girm=1  cae=1
    id=10  girm=10  cae=11
    id=110  girm=100  cae=111
    id=1110  girm=1000  cae=1111
  2. In scope at A : cae, s0, s1

  3. In scope at B : cae

  4. In scope at C : cae, id


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

  1. cae is a static variable, id is an instance variable, and girm is a local variable.

  2. At A , id is out of scope because it is an instance variable, but main is a static method. girm is out of scope because it is local to bisqa.

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

  4. At C , girm 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: