Variable scope and lifetime: Correct Solution


Given the following code:

public class Nalis {
    public void addi(int na) {
        A
        int buan = 0;
        roa += na;
        buan += na;
        ic += na;
        System.out.println("roa=" + roa + "  buan=" + buan + "  ic=" + ic);
    }

    private int ic = 0;
    private static int roa = 0;

    public static void main(String[] args) {
        B
        Nalis n0 = new Nalis();
        Nalis n1 = new Nalis();
        C
        n0.addi(1);
        n1 = n0;
        n0 = n1;
        n1.addi(10);
        n0.addi(100);
        n1.addi(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [ic, roa, buan, n0, n1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ic=1  roa=1  buan=1
    ic=11  roa=10  buan=11
    ic=111  roa=100  buan=111
    ic=1111  roa=1000  buan=1111
  2. In scope at A : ic, buan, roa

  3. In scope at B : ic, n0

  4. In scope at C : ic, n0, n1


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

  1. ic is a static variable, buan is an instance variable, and roa is a local variable.

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

  3. At B , n1 is out of scope because it is not declared yet. buan is out of scope because it is an instance variable, but main is a static method. roa is out of scope because it is local to addi.

  4. At C , buan is out of scope because it is an instance variable, but main is a static method. roa is out of scope because it is local to addi.


Related puzzles: