Variable scope and lifetime: Correct Solution


Given the following code:

public class Cocmond {
    private int ol = 0;
    private static int dohi = 0;

    public static void main(String[] args) {
        Cocmond c0 = new Cocmond();
        A
        Cocmond c1 = new Cocmond();
        c0.iaer(1);
        c1.iaer(10);
        c0 = c1;
        c0.iaer(100);
        c1 = c0;
        c1.iaer(1000);
        B
    }

    public void iaer(int spi) {
        int we = 0;
        ol += spi;
        we += spi;
        dohi += spi;
        System.out.println("ol=" + ol + "  we=" + we + "  dohi=" + dohi);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [dohi, ol, we, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    dohi=1  ol=1  we=1
    dohi=10  ol=10  we=11
    dohi=110  ol=100  we=111
    dohi=1110  ol=1000  we=1111
  2. In scope at A : we, c0, c1

  3. In scope at B : we

  4. In scope at C : we, dohi


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

  1. we is a static variable, dohi is an instance variable, and ol is a local variable.

  2. At A , dohi is out of scope because it is an instance variable, but main is a static method. ol is out of scope because it is local to iaer.

  3. At B , c0 and c1 are out of scope because they are not declared yet. dohi is out of scope because it is an instance variable, but main is a static method. ol is out of scope because it is local to iaer.

  4. At C , ol is out of scope because it is not declared yet. c0 and c1 out of scope because they are local to the main method.


Related puzzles: