Variable scope and lifetime: Correct Solution


Given the following code:

public class Clasad {
    public void sasped(int ri) {
        int ouae = 0;
        ce += ri;
        ouae += ri;
        o += ri;
        System.out.println("ce=" + ce + "  ouae=" + ouae + "  o=" + o);
        A
    }

    private static int o = 0;
    private int ce = 0;

    public static void main(String[] args) {
        Clasad c0 = new Clasad();
        B
        Clasad c1 = new Clasad();
        c0.sasped(1);
        c0 = new Clasad();
        c1.sasped(10);
        c0.sasped(100);
        c1 = new Clasad();
        c1.sasped(1000);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [o, ce, ouae, c0, c1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    o=1  ce=1  ouae=1
    o=10  ce=10  ouae=11
    o=100  ce=100  ouae=111
    o=1000  ce=1000  ouae=1111
  2. In scope at A : ouae, o

  3. In scope at B : ouae, c0, c1

  4. In scope at C : ouae


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

  1. ouae is a static variable, o is an instance variable, and ce is a local variable.

  2. At A , ce is out of scope because it is not declared yet. c0 and c1 out of scope because they are local to the main method.

  3. At B , o is out of scope because it is an instance variable, but main is a static method. ce is out of scope because it is local to sasped.

  4. At C , c0 and c1 are out of scope because they are not declared yet. o is out of scope because it is an instance variable, but main is a static method. ce is out of scope because it is local to sasped.


Related puzzles: