Variable scope and lifetime: Correct Solution


Given the following code:

public class Nodmad {
    public static void main(String[] args) {
        Nodmad n0 = new Nodmad();
        A
        Nodmad n1 = new Nodmad();
        B
        n0.beewth(1);
        n1.beewth(10);
        n0 = new Nodmad();
        n1 = n0;
        n0.beewth(100);
        n1.beewth(1000);
    }

    public void beewth(int re) {
        int ad = 0;
        io += re;
        ad += re;
        ou += re;
        System.out.println("io=" + io + "  ad=" + ad + "  ou=" + ou);
        C
    }

    private static int io = 0;
    private int ou = 0;
}
  1. What does the main method print?
  2. Which of the variables [ou, io, ad, n0, n1] are in scope at A ?
  3. Which are in scope at B ?
  4. Which are in scope at C ?

Solution

  1. Output:

    ou=1  io=1  ad=1
    ou=11  io=10  ad=10
    ou=111  io=100  ad=100
    ou=1111  io=1000  ad=1100
  2. In scope at A : ou, n0, n1

  3. In scope at B : ou, n0, n1

  4. In scope at C : ou, ad


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

  1. ou is a static variable, ad is an instance variable, and io is a local variable.

  2. At A , ad is out of scope because it is an instance variable, but main is a static method. io is out of scope because it is local to beewth.

  3. At B , ad is out of scope because it is an instance variable, but main is a static method. io is out of scope because it is local to beewth.

  4. At C , io is out of scope because it is not declared yet. n0 and n1 out of scope because they are local to the main method.


Related puzzles: