1Z0-808 · Question #79
What is the result? public class StringReplace { public static void main(String[] args) { String message = "Hi everyone!"; System.out.println("message = " + message.replace("e", "X")); } }
The correct answer is B. message = Hi XvXryonX! String.replace(char, char) replaces every occurrence of the target character, so all three 'e' characters in "Hi everyone!" become 'X', yielding "Hi XvXryonX!" - making B correct. Why the distractors are wrong: A - replace() returns a new string with substitutions applied; the…
Question
Options
- Amessage = Hi everyone!
- Bmessage = Hi XvXryonX!
- CA compile time error is produced.
- DA runtime error is produced.
- Emessage =
- Fmessage = Hi Xveryone!
How the community answered
(44 responses)- B93% (41)
- D2% (1)
- F5% (2)
Explanation
String.replace(char, char) replaces every occurrence of the target character, so all three 'e' characters in "Hi everyone!" become 'X', yielding "Hi XvXryonX!" - making B correct.
Why the distractors are wrong:
- A -
replace()returns a new string with substitutions applied; the output is not the original. - C/D - There is no syntax or runtime error;
replace()is a well-defined, null-safe method on a validString. - E -
replace()never empties a string unless every character matches the target. - F - This would only be true if
replace()stopped after the first match, but it doesn't - it replaces all occurrences globally.
Memory tip: Think of String.replace() as "replace all, not one" - unlike regex-based methods where you might limit matches, this method always performs a full sweep of the string from start to finish.
Topics
Community Discussion
No community discussion yet for this question.