Multiple choice technology programming languages

What is the output for the below code ? public class Outer { private String x = "Outer variable"; void doStuff() { String z = "local variable"; class Inner { public void seeOuter() { System.out.println("Outer x is " + x); System.out.println("Local variable z is " + z); } } } }

  1. Outer x is Outer variable.

  2. Compile Error

  3. Local variable z is local variable

  4. Outer x is Outer variable Local variable z is local variable

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

This code attempts to access a local variable z from within a method-local inner class. Local variables accessed by inner classes must be final or effectively final (never reassigned). Since z is a local variable in doStuff() that the Inner class tries to print, this causes a compilation error. The Outer private variable x is accessible, but z violates the final-variable rule for inner classes.

AI explanation

To answer this question, let's go through the code:

public class Outer {
  private String x = "Outer variable";

  void doStuff() {
    String z = "local variable";

    class Inner {
      public void seeOuter() {
        System.out.println("Outer x is " + x);
        System.out.println("Local variable z is " + z);
      }
    }
  }
}

In this code, the class Outer contains a method doStuff() which declares a local variable z of type String.

Inside the doStuff() method, there is also a nested class Inner which has a method seeOuter().

The seeOuter() method tries to access the variables x and z from the enclosing Outer class. However, it is important to note that local variables, like z, are only accessible within the method they are declared in.

Therefore, when trying to access the local variable z from the seeOuter() method, it will result in a compile error because z is not in scope.

So, the correct answer is:

B. Compile Error