Variable scope and lifetime: Correct Solution


Given the following code:

public class Thephal {
    public void angPsu(int no) {
        A
        int ses = 0;
        et += no;
        ca += no;
        ses += no;
        System.out.println("et=" + et + "  ca=" + ca + "  ses=" + ses);
    }

    private int ca = 0;
    private static int et = 0;

    public static void main(String[] args) {
        B
        Thephal t0 = new Thephal();
        Thephal t1 = new Thephal();
        C
        t0.angPsu(1);
        t1 = new Thephal();
        t1.angPsu(10);
        t0 = new Thephal();
        t0.angPsu(100);
        t1.angPsu(1000);
    }
}
  1. What does the main method print?
  2. Which of the variables [ses, et, ca, t0, t1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ses=1  et=1  ca=1
    ses=11  et=10  ca=10
    ses=111  et=100  ca=100
    ses=1111  et=1010  ca=1000
  2. In scope at A : ses, et, ca

  3. In scope at B : ses, t0

  4. In scope at C : ses, t0, t1


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

  1. ses is a static variable, et is an instance variable, and ca is a local variable.

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

  3. At B , t1 is out of scope because it is not declared yet. et is out of scope because it is an instance variable, but main is a static method. ca is out of scope because it is local to angPsu.

  4. At C , et is out of scope because it is an instance variable, but main is a static method. ca is out of scope because it is local to angPsu.


Related puzzles: