Variable scope and lifetime: Correct Solution


Given the following code:

public class Pronlood {
    public static void main(String[] args) {
        A
        Pronlood p0 = new Pronlood();
        Pronlood p1 = new Pronlood();
        B
        p0.ginui(1);
        p1.ginui(10);
        p0.ginui(100);
        p1 = p0;
        p0 = new Pronlood();
        p1.ginui(1000);
    }

    private int irm = 0;
    private static int sti = 0;

    public void ginui(int cebi) {
        C
        int mo = 0;
        irm += cebi;
        sti += cebi;
        mo += cebi;
        System.out.println("irm=" + irm + "  sti=" + sti + "  mo=" + mo);
    }
}
  1. What does the main method print?
  2. Which of the variables [mo, irm, sti, p0, p1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    mo=1  irm=1  sti=1
    mo=10  irm=11  sti=10
    mo=101  irm=111  sti=100
    mo=1101  irm=1111  sti=1000
  2. In scope at A : irm, p0

  3. In scope at B : irm, p0, p1

  4. In scope at C : irm, mo, sti


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

  1. irm is a static variable, mo is an instance variable, and sti is a local variable.

  2. At A , p1 is out of scope because it is not declared yet. mo is out of scope because it is an instance variable, but main is a static method. sti is out of scope because it is local to ginui.

  3. At B , mo is out of scope because it is an instance variable, but main is a static method. sti is out of scope because it is local to ginui.

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


Related puzzles: