Variable scope and lifetime: Correct Solution


Given the following code:

public class Caor {
    private static int ang = 0;

    public static void main(String[] args) {
        Caor c0 = new Caor();
        A
        Caor c1 = new Caor();
        B
        c0.nerDucri(1);
        c1.nerDucri(10);
        c1 = c0;
        c0 = new Caor();
        c0.nerDucri(100);
        c1.nerDucri(1000);
    }

    public void nerDucri(int si) {
        C
        int ent = 0;
        ri += si;
        ent += si;
        ang += si;
        System.out.println("ri=" + ri + "  ent=" + ent + "  ang=" + ang);
    }

    private int ri = 0;
}
  1. What does the main method print?
  2. Which of the variables [ang, ri, ent, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ang=1  ri=1  ent=1
    ang=10  ri=10  ent=11
    ang=100  ri=100  ent=111
    ang=1001  ri=1000  ent=1111
  2. In scope at A : ent, c0, c1

  3. In scope at B : ent, c0, c1

  4. In scope at C : ent, ang, ri


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

  1. ent is a static variable, ang is an instance variable, and ri is a local variable.

  2. At A , ang is out of scope because it is an instance variable, but main is a static method. ri is out of scope because it is local to nerDucri.

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

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


Related puzzles: