Variable scope and lifetime: Correct Solution


Given the following code:

public class RalIght {
    private int asel = 0;
    private static int mai = 0;

    public void datda(int i) {
        int sa = 0;
        A
        sa += i;
        asel += i;
        mai += i;
        System.out.println("sa=" + sa + "  asel=" + asel + "  mai=" + mai);
    }

    public static void main(String[] args) {
        RalIght r0 = new RalIght();
        B
        RalIght r1 = new RalIght();
        C
        r0.datda(1);
        r1 = new RalIght();
        r0 = new RalIght();
        r1.datda(10);
        r0.datda(100);
        r1.datda(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [mai, sa, asel, r0, r1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    mai=1  sa=1  asel=1
    mai=10  sa=10  asel=11
    mai=100  sa=100  asel=111
    mai=1000  sa=1010  asel=1111
  2. In scope at A : asel, sa, mai

  3. In scope at B : asel, r0, r1

  4. In scope at C : asel, r0, r1


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

  1. asel is a static variable, sa is an instance variable, and mai is a local variable.

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

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

  4. At C , sa is out of scope because it is an instance variable, but main is a static method. mai is out of scope because it is local to datda.


Related puzzles: