Bird
0
0

What is wrong with the following code snippet?

medium📝 Debug Q6 of 15
Java - Strings and String Handling
What is wrong with the following code snippet?
String s = "world";
s.substring(1) = "W";
Asubstring() method does not exist in String class
BYou cannot assign a value to the result of substring() because strings are immutable
CThe code correctly changes the substring of s
DYou need to use charAt() instead of substring() to assign a value
Step-by-Step Solution
Solution:
  1. Step 1: Understand substring()

    The substring() method returns a new String and does not allow assignment.
  2. Step 2: Immutability of String

    Strings in Java are immutable, so you cannot modify parts of them directly.
  3. Final Answer:

    You cannot assign a value to the result of substring() because strings are immutable -> Option B
  4. Quick Check:

    Assigning to substring() result is invalid [OK]
Quick Trick: Strings are immutable; substring() returns new string [OK]
Common Mistakes:
  • Trying to assign a value to substring() result
  • Assuming substring() modifies original string
  • Confusing substring() with charAt()

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes