84.3k views
4 votes
Consider the statement below:

StringBuilder sb1 = new StringBuilder(""a toyota"");
Which of the following creates a String object with the value ""toy""?

a. String res = sb1.subString(2, 5);
b. char dest[] = new char[ ()];
sb1.getChars(2, 5, dest, 0);
String res = new String(dest);
c. char dest[] = new char[ ];
dest = sb1.getChars(2, 5);
String res = new String(dest);
d. char dest[] = new char[ ()];
dest = sb1.getChars(0, 3);
String res = new String(dest);"

1 Answer

2 votes

Final answer:

The correct way to create a String object with the value "toy" from the given StringBuilder is option b, which uses the getChars method and then constructs a new String.

Step-by-step explanation:

To create a String object with the value "toy" from a StringBuilder with the content "a toyota", we need to extract the characters from index 2 to 5 (start index is inclusive, end index is exclusive in Java).

Upon reviewing the given options:

Option a. String res = sb1.subString(2, 5); would work but it's misspelled and should be substring, not subString.

Option b. correctly uses getChars method to copy characters into a char array and then creates a new String from that array.

Option c. is incorrect because getChars does not return a value, it is a void method.

Option d. is incorrect because it attempts to copy characters from indices 0 to 3, which would result in "a t" not "toy".

Therefore, the correct option to create a String object with the value "toy" is:

b. char dest[] = new char[3]; sb1.getChars(2, 5, dest, 0); String res = new String(dest);

User Anik Islam Abhi
by
8.5k points