Variable scope and lifetime: Correct Solution


Given the following code:

public class Colsil {
    private int eoc = 0;
    private static int oss = 0;

    public void deoMewcoc(int es) {
        A
        int smad = 0;
        oss += es;
        eoc += es;
        smad += es;
        System.out.println("oss=" + oss + "  eoc=" + eoc + "  smad=" + smad);
    }

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

Solution

  1. Output:

    smad=1  oss=1  eoc=1
    smad=11  oss=10  eoc=10
    smad=111  oss=110  eoc=100
    smad=1111  oss=1000  eoc=1000
  2. In scope at A : smad, oss, eoc

  3. In scope at B : smad, c0

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


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

  1. smad is a static variable, oss is an instance variable, and eoc 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. oss is out of scope because it is an instance variable, but main is a static method. eoc is out of scope because it is local to deoMewcoc.

  4. At C , oss is out of scope because it is an instance variable, but main is a static method. eoc is out of scope because it is local to deoMewcoc.


Related puzzles: