What is the result?

Given a code fragment:
<code>
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”);
}
</code>
What is the result?

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



Leave a Reply 4

Your email address will not be published. Required fields are marked *


Marin R

Marin R

Correct answer is B

Deepak

Deepak

Correct answer is D. W of string h1 is capital while that of Sb is small

Kalil Peixoto

Kalil Peixoto

It’s true Deepak, the correct one is D.

Rolandas

Rolandas

It seem they wanted to say that h1.equals(sb.toString()) and sb.equals(h1.toString()) are different things 🙂