Given a code fragment:
StringBuilder sb = new StringBuilder ();
String h1 = "HelloWorld";
sb.append("Hello").append ("world");
if (h1 == sb.toString()) {
System.out.println("They match");
}
if (h1.equals(sb.toString())) {
System.out.println("They really match");
}
What is the result?
A.
They match
They really match
B.
They really match
C.
They match
D.
Nothing is printed to the screen
Explanation:
Strings can not be compared with the usual <, <=, >, or >= operators, and the == and != operators
don’t compare the characters in the strings. So the first if statement fails.
Equals works fine on strings. But it does not work here.The second if-statement also fails. The
StringBuffer class does not override the equals method so it uses the equals method of Object.
If a and b are two objects from a class which doesn’t override equals, then
a.equals(b) is the same as a == b
Correct answer is B
Correct answer is D. W of string h1 is capital while that of Sb is small
It’s true Deepak, the correct one is D.
It seem they wanted to say that h1.equals(sb.toString()) and sb.equals(h1.toString()) are different things 🙂