Variable scope and lifetime: Correct Solution


Given the following code:

public class Seng {
    public static void main(String[] args) {
        A
        Seng s0 = new Seng();
        Seng s1 = new Seng();
        B
        s0.idnom(1);
        s1 = new Seng();
        s1.idnom(10);
        s0 = s1;
        s0.idnom(100);
        s1.idnom(1000);
    }

    public void idnom(int za) {
        int en = 0;
        C
        ded += za;
        en += za;
        seul += za;
        System.out.println("ded=" + ded + "  en=" + en + "  seul=" + seul);
    }

    private static int seul = 0;
    private int ded = 0;
}
  1. What does the main method print?
  2. Which of the variables [seul, ded, en, s0, s1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    seul=1  ded=1  en=1
    seul=10  ded=10  en=11
    seul=110  ded=100  en=111
    seul=1110  ded=1000  en=1111
  2. In scope at A : en, s0

  3. In scope at B : en, s0, s1

  4. In scope at C : en, seul, ded


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

  1. en is a static variable, seul is an instance variable, and ded is a local variable.

  2. At A , s1 is out of scope because it is not declared yet. seul is out of scope because it is an instance variable, but main is a static method. ded is out of scope because it is local to idnom.

  3. At B , seul is out of scope because it is an instance variable, but main is a static method. ded is out of scope because it is local to idnom.

  4. At C , s0 and s1 out of scope because they are local to the main method.


Related puzzles: