Java OCA OCP Practice Question 2453

Question

Given:

1. public class Main {  
2.   public static void main(String[] args) {  
3.     String s = "";  
4.     StringBuffer sb1 = new StringBuffer("hi");  
5.     StringBuffer sb2 = new StringBuffer("hi");  
6.     StringBuffer sb3 = new StringBuffer(sb2);    
7.     StringBuffer sb4 = sb3;  /*from  w w  w .j  a  v a  2  s.  c o m*/
8.     if(sb1.equals(sb2)) s += "1 ";  
9.     if(sb2.equals(sb3)) s += "2 ";  
10.     if(sb3.equals(sb4)) s += "3 ";  
11.     String s2 = "hi";  
12.     String s3 = "hi";  
13.     String s4 = s3;  
14.     if(s2.equals(s3)) s += "4 ";  
15.     if(s3.equals(s4)) s += "5 ";  
16.     System.out.println(s);  
17.   }  
18. } 

What is the result?

  • A. 1 3
  • B. 1 5
  • C. 1 2 3
  • D. 1 4 5
  • E. 3 4 5
  • F. 1 3 4 5
  • G. 1 2 3 4 5
  • H. Compilation fails.


E is correct.

Note

The StringBuffer class doesn't override the equals() method, so two different StringBuffer objects with the same value will not be equal according to the equals() method.

On the other hand, the String class's equals() method has been overridden so that two different String objects with the same value will be considered equal according to the equals() method.




PreviousNext

Related