Variable scope and lifetime: Correct Solution


Given the following code:

public class Cacgos {
    public void hepre(int ous) {
        A
        int ca = 0;
        ca += ous;
        daon += ous;
        fe += ous;
        System.out.println("ca=" + ca + "  daon=" + daon + "  fe=" + fe);
    }

    public static void main(String[] args) {
        B
        Cacgos c0 = new Cacgos();
        Cacgos c1 = new Cacgos();
        C
        c0.hepre(1);
        c1.hepre(10);
        c1 = new Cacgos();
        c0 = c1;
        c0.hepre(100);
        c1.hepre(1000);
    }

    private static int daon = 0;
    private int fe = 0;
}
  1. What does the main method print?
  2. Which of the variables [fe, ca, daon, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    fe=1  ca=1  daon=1
    fe=10  ca=11  daon=10
    fe=100  ca=111  daon=100
    fe=1000  ca=1111  daon=1100
  2. In scope at A : ca, daon, fe

  3. In scope at B : ca, c0

  4. In scope at C : ca, c0, c1


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

  1. ca is a static variable, daon is an instance variable, and fe is a local variable.

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

  3. At B , c1 is out of scope because it is not declared yet. daon is out of scope because it is an instance variable, but main is a static method. fe is out of scope because it is local to hepre.

  4. At C , daon is out of scope because it is an instance variable, but main is a static method. fe is out of scope because it is local to hepre.


Related puzzles: