Variable scope and lifetime: Correct Solution


Given the following code:

public class IniParspoc {
    private int ca = 0;

    public static void main(String[] args) {
        A
        IniParspoc i0 = new IniParspoc();
        IniParspoc i1 = new IniParspoc();
        B
        i0.sciglu(1);
        i1.sciglu(10);
        i1 = new IniParspoc();
        i0 = new IniParspoc();
        i0.sciglu(100);
        i1.sciglu(1000);
    }

    public void sciglu(int idit) {
        int al = 0;
        C
        a += idit;
        ca += idit;
        al += idit;
        System.out.println("a=" + a + "  ca=" + ca + "  al=" + al);
    }

    private static int a = 0;
}
  1. What does the main method print?
  2. Which of the variables [al, a, ca, i0, i1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    al=1  a=1  ca=1
    al=11  a=10  ca=10
    al=111  a=100  ca=100
    al=1111  a=1000  ca=1000
  2. In scope at A : al, i0

  3. In scope at B : al, i0, i1

  4. In scope at C : al, a, ca


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

  1. al is a static variable, a is an instance variable, and ca is a local variable.

  2. At A , i1 is out of scope because it is not declared yet. a is out of scope because it is an instance variable, but main is a static method. ca is out of scope because it is local to sciglu.

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

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


Related puzzles: