Java OCA OCP Practice Question 2126

Question

What is the output of the following?.

package mypkg; /*w  w w.  ja va2 s  .c om*/
import java.util.*; 


public class MyResouceBundle extends ListResourceBundle { 
   private int count = 0; 
   @Override 
   protected Object[][] getContents() { 
      return new Object[][] {{ "count", new MyResouceBundle() }}; 
   } 
   public int getCount() { 
      return count++; 
   } 
   public static void main(String[] args) { 
      ResourceBundle rb = ResourceBundle.getBundle("mypkg.MyResouceBundle"); 
      MyResouceBundle obj = (MyResouceBundle) rb.getObject("count"); 
      System.out.println(obj.getCount() + " " + obj.getCount()); 
   } 
} 
  • A. 0 0
  • B. 0 1
  • C. The code does not compile.
  • D. The code compiles but throws an exception at runtime.


B.

Note

This class correctly creates a Java class resource bundle.

It extends ListResourceBundle and creates a 2D array as the property contents.

In the main() method, it gets the resource bundle without a locale and requests the count key.

Since this is a Java Object, it calls getObject() to get the value and casts it to the correct type.

Then the getCount() method is called twice, incrementing each time, making Option B the correct answer.

Note that having a mutable object as a property is a bad practice.




PreviousNext

Related