Variable scope and lifetime: Correct Solution


Given the following code:

public class Frahe {
    private int crar = 0;
    private static int saor = 0;

    public static void main(String[] args) {
        A
        Frahe f0 = new Frahe();
        Frahe f1 = new Frahe();
        B
        f0.carial(1);
        f1 = new Frahe();
        f1.carial(10);
        f0 = f1;
        f0.carial(100);
        f1.carial(1000);
    }

    public void carial(int a) {
        C
        int rau = 0;
        saor += a;
        rau += a;
        crar += a;
        System.out.println("saor=" + saor + "  rau=" + rau + "  crar=" + crar);
    }
}
  1. What does the main method print?
  2. Which of the variables [crar, saor, rau, f0, f1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    crar=1  saor=1  rau=1
    crar=11  saor=10  rau=10
    crar=111  saor=100  rau=110
    crar=1111  saor=1000  rau=1110
  2. In scope at A : crar, f0

  3. In scope at B : crar, f0, f1

  4. In scope at C : crar, rau, saor


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

  1. crar is a static variable, rau is an instance variable, and saor is a local variable.

  2. At A , f1 is out of scope because it is not declared yet. rau is out of scope because it is an instance variable, but main is a static method. saor is out of scope because it is local to carial.

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

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


Related puzzles: