109k views
2 votes
Consider the String below:

String r = ""a toyota"";
Which of the following will create the String r1 = ""a TOYOTa""?

a. String r1 = r.replace(""toyot"", TOYOT"");
b. String r1 = r.replace('t','T');
r1 = r.replace('o','0');
r1 = r.replace('y','Y');
c. String r1 = r.replace('t','T').replace('o', '0').replace('y', 'Y');
d. String r1 = r.substring(2, 4).toUpperCase();"

1 Answer

3 votes

Final answer:

To create the String r1 = "a TOYOTa" from the original String r = "a toyota", the correct Java code snippet would be "String r1 = r.replace('t','T').replace('o', '0').replace('y', 'Y');", thus option c is the correct answer.

Step-by-step explanation:

To manipulate a String in Java to create a new String with certain characteristics. Specifically, they want to create the String r1 which has the value "a TOYOTa" from the original String r which is "a toyota". Looking at the code snippets provided:

  • a. String r1 = r.replace("toyot", "TOYOT"); - This would replace the substring "toyot" with "TOYOT", which is not what we need.
  • b. String r1 = r.replace('t','T'); r1 = r.replace('o','0'); r1 = r.replace('y','Y'); - This code does not chain the replace method calls; instead, it overwrites r1 with each call, so only the final replace would take effect.
  • c. String r1 = r.replace('t','T').replace('o', '0').replace('y', 'Y'); - This correctly chains the replace calls and would create the desired r1 "a TOYOTa".
  • d. String r1 = r.substring(2, 4).toUpperCase(); - This takes a substring of r from index 2 to 4 and converts it to uppercase. This does not yield the full required String.

Therefore, the correct answer is c. String r1 = r.replace('t','T').replace('o', '0').replace('y', 'Y');.

User Vomi
by
10.0k points