Java OCA OCP Practice Question 2182

Question

Which statements about the following class are true?

package mypkg; //from  w  ww . ja v a 2s . c o  m
import java.io.*; 
public class Main { 
   public void clearPassword(char[] password) { 
      for(int i=0; i<password.length; i++) { 
         password[i] = 0; 
      } 
   } 
   public String getPassword() { 
      Console c = System.console(); 
      final char[] pass = c.readPassword("Enter your password: "); 
      StringBuilder sb = new StringBuilder(); 
      for(char p : pass) { 
         sb.append(p); 
      } 
      clearPassword(pass); 
      return sb.toString(); 
   } 

   public static void main(String[] webMain) { 
      String pass = new Main().getPassword(); 
   } 
} 
  • I. The class compiles.
  • II. The design protects the password by clearing it from memory after it is entered.
  • III. The class may throw an exception at runtime.
  • A. I only
  • B. II only
  • C. I and II only
  • D. I and III only
  • E. I, II, and III


D.

Note

The code compiles without issue, making the first statement true and eliminating Option B.

It is possible that System.console() could return null, leading to a NullPointerException at runtime and making the third statement true.

For this reason, Options A and C are also incorrect.

That leaves us with two choices.

While the process correctly clears the password from the char array in memory, it adds the value to the JVM string pool when it is converted to a String.

The whole point of using a char array is to prevent the password from entering the JVM string pool, where it can exist after the method that called it has finished running.

For this reason, the second statement is false, making Option D correct and Option E incorrect.




PreviousNext

Related