1Z0-803 · Question #95
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!. The String.replace() method replaces all occurrences of the specified character sequence 'e' with 'X' in the original string "Hi everyone!".
Question
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")); } }
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
(38 responses)- A3% (1)
- B89% (34)
- D3% (1)
- E5% (2)
Why each option
The `String.replace()` method replaces all occurrences of the specified character sequence 'e' with 'X' in the original string "Hi everyone!".
This choice incorrectly suggests that no replacement occurs, failing to apply the `replace()` method's functionality.
The `replace("e", "X")` method on the string "Hi everyone!" replaces all three occurrences of the lowercase character 'e' with 'X', yielding "Hi XvXryonX!".
The code is syntactically correct and will compile successfully without any compilation errors.
The code does not contain any operations that would typically lead to a runtime error in this simple string manipulation.
This choice incorrectly implies that the string becomes empty or significantly altered beyond character replacement.
This choice incorrectly suggests that only a single or partial replacement of 'e' occurs; `replace()` replaces all occurrences.
Concept tested: Java String.replace() method
Source: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#replace(java.lang.CharSequence,java.lang.CharSequence)
Topics
Community Discussion
No community discussion yet for this question.