Challenge - 5 Problems
String Immutability Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output of this Java code involving String immutability?
Consider the following Java code snippet. What will be printed when it runs?
Java
public class Test { public static void main(String[] args) { String s = "hello"; s.toUpperCase(); System.out.println(s); } }
Attempts:
2 left
💡 Hint
Remember that Strings in Java cannot be changed once created.
✗ Incorrect
The method toUpperCase() returns a new String object with uppercase letters but does not change the original String. Since s is not reassigned, it still holds "hello".
❓ Predict Output
intermediateWhat does this code print after String concatenation?
Look at this Java code. What will be printed?
Java
public class Test { public static void main(String[] args) { String s = "cat"; s += "dog"; System.out.println(s); } }
Attempts:
2 left
💡 Hint
String concatenation creates a new String object.
✗ Incorrect
The += operator creates a new String "catdog" and assigns it back to s. So s now points to "catdog".
🔧 Debug
advancedWhich option causes a compilation error due to String immutability?
Which of the following Java code snippets will cause a compilation error?
Attempts:
2 left
💡 Hint
Think about whether you can assign a character to a position in a String.
✗ Incorrect
Strings are immutable in Java. You cannot assign a character to an index like s.charAt(0) = 'H'; causes a compilation error.
🧠 Conceptual
advancedHow does Java handle String immutability internally?
Which statement best describes how Java implements String immutability?
Attempts:
2 left
💡 Hint
Think about what 'final' means in Java and how it relates to immutability.
✗ Incorrect
Java stores String characters in a final char array inside the String object. This array cannot be changed after the String is created, ensuring immutability.
❓ Predict Output
expertWhat is the output of this Java code involving String references?
Analyze the code below. What will be printed?
Java
public class Test { public static void main(String[] args) { String a = "abc"; String b = a; a = a + "d"; System.out.println(b); } }
Attempts:
2 left
💡 Hint
Consider what happens to the original String reference when you concatenate.
✗ Incorrect
When a is concatenated with "d", a points to a new String "abcd". But b still points to the original String "abc".
