Bird
0
0

You want to replace all spaces in a string with underscores and keep the original string unchanged. Which approach is correct?

hard📝 Application Q8 of 15
Java - Strings and String Handling
You want to replace all spaces in a string with underscores and keep the original string unchanged. Which approach is correct?
AModify characters in original string directly
BUse <code>original.replace(' ', '_');</code> without assignment
CUse <code>original.toCharArray()</code> and change spaces to underscores in array
DUse <code>newString = original.replace(' ', '_');</code> and keep original as is
Step-by-Step Solution
Solution:
  1. Step 1: Understand string immutability

    Original string cannot be changed; methods return new strings.
  2. Step 2: Correct way to replace characters

    Assign the result of replace() to a new string variable to keep original unchanged.
  3. Final Answer:

    Use newString = original.replace(' ', '_'); and keep original as is -> Option D
  4. Quick Check:

    Assign replace() result to new string to keep original [OK]
Quick Trick: Assign replace() result to new variable; original stays unchanged [OK]
Common Mistakes:
  • Calling replace() without assignment and expecting change
  • Trying to modify original string characters directly
  • Using toCharArray() but not converting back to string

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes