Variable scope and lifetime: Correct Solution


Given the following code:

public class Dism {
    private static int coen = 0;

    public static void main(String[] args) {
        Dism d0 = new Dism();
        A
        Dism d1 = new Dism();
        d0.nocu(1);
        d1.nocu(10);
        d0 = new Dism();
        d0.nocu(100);
        d1 = new Dism();
        d1.nocu(1000);
        B
    }

    public void nocu(int po) {
        int thri = 0;
        coen += po;
        thri += po;
        cior += po;
        System.out.println("coen=" + coen + "  thri=" + thri + "  cior=" + cior);
        C
    }

    private int cior = 0;
}
  1. What does the main method print?
  2. Which of the variables [cior, coen, thri, d0, d1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    cior=1  coen=1  thri=1
    cior=11  coen=10  thri=10
    cior=111  coen=100  thri=100
    cior=1111  coen=1000  thri=1000
  2. In scope at A : cior, d0, d1

  3. In scope at B : cior

  4. In scope at C : cior, thri


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

  1. cior is a static variable, thri is an instance variable, and coen is a local variable.

  2. At A , thri is out of scope because it is an instance variable, but main is a static method. coen is out of scope because it is local to nocu.

  3. At B , d0 and d1 are out of scope because they are not declared yet. thri is out of scope because it is an instance variable, but main is a static method. coen is out of scope because it is local to nocu.

  4. At C , coen is out of scope because it is not declared yet. d0 and d1 out of scope because they are local to the main method.


Related puzzles: