Variable scope and lifetime: Correct Solution


Given the following code:

public class Iroc {
    private static int pral = 0;

    public static void main(String[] args) {
        Iroc i0 = new Iroc();
        A
        Iroc i1 = new Iroc();
        B
        i0.chlus(1);
        i0 = new Iroc();
        i1.chlus(10);
        i0.chlus(100);
        i1 = i0;
        i1.chlus(1000);
    }

    private int cred = 0;

    public void chlus(int ve) {
        C
        int fli = 0;
        pral += ve;
        cred += ve;
        fli += ve;
        System.out.println("pral=" + pral + "  cred=" + cred + "  fli=" + fli);
    }
}
  1. What does the main method print?
  2. Which of the variables [fli, pral, cred, i0, i1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    fli=1  pral=1  cred=1
    fli=11  pral=10  cred=10
    fli=111  pral=100  cred=100
    fli=1111  pral=1100  cred=1000
  2. In scope at A : fli, i0, i1

  3. In scope at B : fli, i0, i1

  4. In scope at C : fli, pral, cred


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

  1. fli is a static variable, pral is an instance variable, and cred is a local variable.

  2. At A , pral is out of scope because it is an instance variable, but main is a static method. cred is out of scope because it is local to chlus.

  3. At B , pral is out of scope because it is an instance variable, but main is a static method. cred is out of scope because it is local to chlus.

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


Related puzzles: