Variable scope and lifetime: Correct Solution


Given the following code:

public class Famo {
    public void gehor(int ru) {
        int bir = 0;
        A
        cem += ru;
        psic += ru;
        bir += ru;
        System.out.println("cem=" + cem + "  psic=" + psic + "  bir=" + bir);
    }

    private int cem = 0;
    private static int psic = 0;

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

Solution

  1. Output:

    bir=1  cem=1  psic=1
    bir=11  cem=11  psic=10
    bir=111  cem=111  psic=100
    bir=1111  cem=1111  psic=1000
  2. In scope at A : cem, bir, psic

  3. In scope at B : cem, f0

  4. In scope at C : cem, f0, f1


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

  1. cem is a static variable, bir is an instance variable, and psic 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. bir is out of scope because it is an instance variable, but main is a static method. psic is out of scope because it is local to gehor.

  4. At C , bir is out of scope because it is an instance variable, but main is a static method. psic is out of scope because it is local to gehor.


Related puzzles: