which code fragment is the best potion to build and print the following string…?

Given the code fragment:
String name = “Spot”;
int age = 4;
String str =”My dog ” + name + ” is ” + age;
System.out.println(str);
And
StringBuilder sb = new StringBuilder();
Using StringBuilder, which code fragment is the best potion to build and print the following string
My dog Spot is 4

Given the code fragment:
String name = “Spot”;
int age = 4;
String str =”My dog ” + name + ” is ” + age;
System.out.println(str);
And
StringBuilder sb = new StringBuilder();
Using StringBuilder, which code fragment is the best potion to build and print the following string
My dog Spot is 4

A.
sb.append(“My dog ” + name + ” is ” + age);
System.out.println(sb);

B.
sb.insert(“My dog “).append( name + ” is ” + age); System.out.println(sb);

C.
sb.insert(“My dog “).insert( name ).insert(” is ” ).insert(age); System.out.println(sb);

D.
sb.append(“My dog “).append( name ).append(” is ” ).append(age); System.out.println(sb);



Leave a Reply 6

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


Edward

Edward

This is a single choice question=_=||. Only D is right ,because if we print A , the result is “MydogSpotis4” without blanks.

Ivan

Ivan

Edward:

Did you take this exam recently? Are these the actual exam questions? Thanks!

lolwut?

lolwut?

Ed, how do you know it was a single choice question?

You took the exam and remembered this one?

What if this one was the one you got wrong(you don’t really know since they never tell you what questions you got wrong) because you didn’t notice it said at the bottom : CHOOSE ALL THAT APPLY?

And as far as A being wrong, you said the result would be that without blanks. Take a good HARD AND LOOONG look at ‘A’, Edward. *THERE ARE BLANKS IN THE STRINGS*!!! Therefore, if that was printed out, the SAME result as in ‘D’ would be created.

Noname

Noname

Anyway, the right answed is D. There we use a StringBuilder instance to merge all that particles together. The main trick is that with StringBuilder we don’t need to create new String objects every time we do concatenation. So we save memory and that is fine.

Luis Fernando Rosero Zapata

Luis Fernando Rosero Zapata

The best answered is D. Although A gives the same result is no the best option.

Naira

Naira

The answer is D.

A is not the best option: it still creates new String object while concatenation.