Variable scope and lifetime: Correct Solution


Given the following code:

public class Osti {
    public void rarIdborm(int ict) {
        A
        int thuc = 0;
        lu += ict;
        cral += ict;
        thuc += ict;
        System.out.println("lu=" + lu + "  cral=" + cral + "  thuc=" + thuc);
    }

    private static int cral = 0;

    public static void main(String[] args) {
        Osti o0 = new Osti();
        B
        Osti o1 = new Osti();
        C
        o0.rarIdborm(1);
        o1 = o0;
        o1.rarIdborm(10);
        o0.rarIdborm(100);
        o0 = o1;
        o1.rarIdborm(1000);
    }

    private int lu = 0;
}
  1. What does the main method print?
  2. Which of the variables [thuc, lu, cral, o0, o1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    thuc=1  lu=1  cral=1
    thuc=11  lu=11  cral=10
    thuc=111  lu=111  cral=100
    thuc=1111  lu=1111  cral=1000
  2. In scope at A : lu, thuc, cral

  3. In scope at B : lu, o0, o1

  4. In scope at C : lu, o0, o1


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

  1. lu is a static variable, thuc is an instance variable, and cral is a local variable.

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

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

  4. At C , thuc is out of scope because it is an instance variable, but main is a static method. cral is out of scope because it is local to rarIdborm.


Related puzzles: