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, thena.equals(b) is the same as
a == b
The correct answer is: b
Yes the correct answer is d. I didn’t pay attention to w and W
That makes no difference(w and W).
The explanation above says it plain and simple.
You can’t compare strings using relational operators anyway.
Walaa is correct, the answer is d. It is “equals” but not “equalsIgnoreCase” in the second “if” clause.
I just tested this with eclipse!
If “World” is written with a big “W”, the correct answer is B
If “world” is written with a small “w”, the correct answer is D
So depense how this would be written!
—-
And to clarify the mess about the equals:
In the example the question is about a “STRING BUILDER”. The explanation is talking in the second part about the “STRING BUFFER”. This are different things. The explanation is true, but only for the Buffer. For this reason you can use equals with the “STRING BUILDER”.
-> so you can compare (equals) StringBuilder with Strings, if you you the .toString() method on the String builder!
The sb.toString()returns the String class. Both h1 and sb.toString() are String class, so they can use (equals) to compare. The statment h1.equals(sb.toString()) or sb.toString().equals(h1) return the same results.