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 (sb.equals(h1)) {
System.out.println(“They really match”);
}

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 (sb.equals(h1)) {
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 7

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


Jazz

Jazz

D

Explanation:

Because if((sb.equals(h1))) -> returns false.

if (h1.equals(sb.toString())) { //returns true
System.out.println(“They really match”);
}

Then we will have Output as : “They really match”.

James

James

The Answer is D.

If line 7 were changed to

if (sb.toString().equals(h1)) {

or

if (h1.equals(sb.toString())) {

the code would print:
They really match

The equals method of an object checks to make sure that the objects being compared are of the same type and contain the same data. You can’t directly compare a StringBuilder object with a String object.

Google

Google

Check beneath, are some totally unrelated web-sites to ours, even so, they’re most trustworthy sources that we use.

East Hartford Taxes

East Hartford Taxes

check beneath, are some totally unrelated internet websites to ours, having said that, they’re most trustworthy sources that we use

make an app

make an app

here are some hyperlinks to websites that we link to mainly because we think they may be really worth visiting

free easy legitimate work from home jobs

free easy legitimate work from home jobs

we prefer to honor many other world wide web web pages on the web, even if they arent linked to us, by linking to them. Below are some webpages worth checking out