Variable scope and lifetime: Correct Solution


Given the following code:

public class Froho {
    private int aun = 0;
    private static int uzin = 0;

    public void dieng(int bu) {
        A
        int se = 0;
        uzin += bu;
        aun += bu;
        se += bu;
        System.out.println("uzin=" + uzin + "  aun=" + aun + "  se=" + se);
    }

    public static void main(String[] args) {
        B
        Froho f0 = new Froho();
        Froho f1 = new Froho();
        f0.dieng(1);
        f0 = new Froho();
        f1.dieng(10);
        f1 = f0;
        f0.dieng(100);
        f1.dieng(1000);
        C
    }
}
  1. What does the main method print?
  2. Which of the variables [se, uzin, aun, f0, f1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    se=1  uzin=1  aun=1
    se=11  uzin=10  aun=10
    se=111  uzin=100  aun=100
    se=1111  uzin=1100  aun=1000
  2. In scope at A : se, uzin, aun

  3. In scope at B : se, f0

  4. In scope at C : se


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

  1. se is a static variable, uzin is an instance variable, and aun is a local variable.

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

  3. At B , f1 is out of scope because it is not declared yet. uzin is out of scope because it is an instance variable, but main is a static method. aun is out of scope because it is local to dieng.

  4. At C , f0 and f1 are out of scope because they are not declared yet. uzin is out of scope because it is an instance variable, but main is a static method. aun is out of scope because it is local to dieng.


Related puzzles: