OCA Java SE 8 Exception - OCA Mock Question Exception 1








Question

Which exception will the following throw?

     Object obj = new Integer(3); 
     String str = (String) obj; 
     System.out.println(str); 
  1. ArrayIndexOutOfBoundsException
  2. ClassCastException
  3. IllegalArgumentException
  4. NumberFormatException
  5. None of the above.




Answer



B.

Note

The second line tries to cast an Integer to a String and throws ClassCastException.

public class Main {
  public static void main(String[] args) {
    Object obj = new Integer(3); 
    String str = (String) obj; 
    System.out.println(str); 

  }
}

The code above generates the following result.