Java OCA OCP Practice Question 1508

Question

What is the output of the following application?

package mypkg; //from w  w w.  ja va2s.c o m
public class Main { 
   private int level = 1; 
   class Deep { 
      private int level = 2; 
      class Deeper { 
         private int level = 5; 
         public void print() { 
            System.out.print(level); 
            System.out.print(" "+Main.Deep.this.level); 
            System.out.print(" "+Deep.this.level); 
         } 
      } 
   } 
   public static void main(String[] bots) { 
      Main.Deep.Deeper simulation = new Main().new Deep().new Deeper(); 
      simulation.print(); 
   } 
} 
  • A. 1 1 2
  • B. 5 2 2
  • C. 5 2 1
  • D. The code does not compile.


B.

Note

The code compiles without issue, so Option D is incorrect.

The first print() statement refers to value in the Deeper class, so 5 is printed.

The second and third print() statements actually refer to the same value in the Deep class, so 2 is printed twice.

The prefix Main. is unnecessary in the first of the two print() statements and does not change the result.

Option B is the correct answer.




PreviousNext

Related