Java OCA OCP Practice Question 972

Question

Which one statement is true about the following code fragment?

1. String s = "abcde"; 
2. StringBuffer s1 = new StringBuffer("abcde"); 
3. if (s.equals(s1)) 
4.     s1 = null; 
5. if (s1.equals(s)) 
6.     s = null; 
  • A. Compilation fails at line 1 because the String constructor must be called explicitly.
  • B. Compilation fails at line 3 because s and s1 have different types.
  • C. Compilation succeeds. During execution, an exception is thrown at line 3.
  • D. Compilation succeeds. During execution, an exception is thrown at line 5.
  • E. Compilation succeeds. No exception is thrown during execution.


E.

Note

A is wrong because line 1 is a perfectly acceptable way to create a String and is actually more efficient than explicitly calling the constructor.

B is wrong because the argument to the equals() method is of type Object; thus any object reference or array variable may be passed.

The calls on lines 3 and 5 return false without throwing exceptions because s and s1 are objects of different types.




PreviousNext

Related