Variable scope and lifetime: Correct Solution


Given the following code:

public class Vaura {
    private int ke = 0;

    public void achpe(int be) {
        A
        int ca = 0;
        ca += be;
        pran += be;
        ke += be;
        System.out.println("ca=" + ca + "  pran=" + pran + "  ke=" + ke);
    }

    public static void main(String[] args) {
        B
        Vaura v0 = new Vaura();
        Vaura v1 = new Vaura();
        C
        v0.achpe(1);
        v1.achpe(10);
        v1 = new Vaura();
        v0 = new Vaura();
        v0.achpe(100);
        v1.achpe(1000);
    }

    private static int pran = 0;
}
  1. What does the main method print?
  2. Which of the variables [ke, ca, pran, v0, v1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ke=1  ca=1  pran=1
    ke=10  ca=11  pran=10
    ke=100  ca=111  pran=100
    ke=1000  ca=1111  pran=1000
  2. In scope at A : ca, pran, ke

  3. In scope at B : ca, v0

  4. In scope at C : ca, v0, v1


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

  1. ca is a static variable, pran is an instance variable, and ke is a local variable.

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

  3. At B , v1 is out of scope because it is not declared yet. pran is out of scope because it is an instance variable, but main is a static method. ke is out of scope because it is local to achpe.

  4. At C , pran is out of scope because it is an instance variable, but main is a static method. ke is out of scope because it is local to achpe.


Related puzzles: