Search This Blog

Wednesday, February 2, 2011

Question 23

What will happen when you attempt to compile and run the given code?

public class StringEquals {
  public static void main(String[] args) {
    Boolean b = new Boolean(true);
    String str = new String(""+b);
    StringBuffer sb = new StringBuffer(str);
    System.out.println(b.equals(str)+","
          +str.equals(sb)+","+sb.equals(b));
  }
}
Options:

a. It will print - false, true, false
b. It will print - true, true, false
c. It will print - false, false, false
d. It will print - true, false, false
e. Compilation error
f. ClassCastException at runtime





Answer : C

To answer this question, first one should have to know how equals() method is implemented.

public boolean equals(Object obj){ 
  if(obj != null && obj instaceOf ClassOfComparing) {
      //implement logic of comparison like type cast the obj to classOfComparing and do necessary checks.  
  }
  else{
   return false;

}

The above mentioned code is not mandatory, but in java classes like String, Boolean and StringBuffer implemented it in that fashion.

So based on that the first if condition none of the classes are of instances of other. So options A,B,D are incorrect. ClassCastException is not thrown because the if statement check whether the object is a classOfComparing or not.


Question 23SocialTwist Tell-a-Friend

No comments:

Post a Comment