Bird
Raised Fist0
Javaprogramming~10 mins

String immutability in Java - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - String immutability
Create String s = "Hello"
↓
Try to change s by s.concat(" World")
↓
New String created with "Hello World"
↓
Original s still "Hello"
↓
Assign new String to s if desired
↓
s now points to new String or old String remains
When you try to change a String, Java creates a new String object instead of changing the original one.
Execution Sample
Java
String s = "Hello";
s.concat(" World");
System.out.println(s);
s = s.concat(" World");
System.out.println(s);
This code shows that calling concat does not change the original String unless reassigned.
Execution Table
StepCode executedString s valueActionOutput
1String s = "Hello";"Hello"Create s with "Hello"
2s.concat(" World");"Hello"Create new String "Hello World" but do not assign
3System.out.println(s);"Hello"Print sHello
4s = s.concat(" World");"Hello World"Assign new String to s
5System.out.println(s);"Hello World"Print sHello World
💡 Program ends after printing both values of s showing immutability effect
Variable Tracker
VariableStartAfter Step 2After Step 4Final
s"Hello""Hello""Hello World""Hello World"
Key Moments - 2 Insights
Why does s.concat(" World") not change s immediately?
Because Strings are immutable in Java, concat creates a new String but does not change the original s unless you assign the result back to s (see step 2 and 4 in execution_table).
What happens if you print s right after s.concat(" World") without assignment?
The original s remains unchanged and prints "Hello" as shown in step 3 of execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of s after step 2?
A"Hello"
B"Hello World"
Cnull
DCompilation error
💡 Hint
Check the 'String s value' column at step 2 in execution_table
At which step does s actually change to "Hello World"?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the 'Action' and 'String s value' columns in execution_table
If we remove the assignment in step 4, what will be printed at step 5?
A"Hello World"
Bnull
C"Hello"
DRuntime error
💡 Hint
Refer to step 3 and 5 outputs in execution_table when no assignment is done
Concept Snapshot
String immutability in Java means once a String is created, it cannot be changed.
Methods like concat() create new Strings instead of modifying the original.
To update a String variable, assign the new String back to it.
Example:
String s = "Hi";
s = s.concat(" there"); // s now "Hi there"
Full Transcript
This visual trace shows how Java Strings are immutable. When we create a String s with "Hello", it holds that value. Calling s.concat(" World") creates a new String "Hello World" but does not change s itself. Only when we assign the result back to s does s point to the new String. Printing s before assignment shows the original value. This teaches that String methods that seem to change the String actually return new Strings, preserving immutability.

Practice

(1/5)
1. What does it mean that a String in Java is immutable?
easy
A. Once created, the string cannot be changed.
B. The string can be changed anytime.
C. The string changes automatically when printed.
D. The string can only be changed inside loops.

Solution

  1. Step 1: Understand the meaning of immutability

    Immutability means the object cannot be changed after creation.
  2. Step 2: Apply this to Java Strings

    Java strings cannot be modified once created; any change creates a new string.
  3. Final Answer:

    Once created, the string cannot be changed. -> Option A
  4. Quick Check:

    String immutability = cannot change after creation [OK]
Hint: Immutable means no change allowed after creation [OK]
Common Mistakes:
  • Thinking strings can be changed directly
  • Confusing immutability with constant variables
  • Assuming strings change when printed
2. Which of the following is the correct way to create a new string by changing a character in an existing string str?
easy
A. str.charAt(0) = 'A';
B. str[0] = 'A';
C. str = "A" + str.substring(1);
D. str.replaceChar(0, 'A');

Solution

  1. Step 1: Check syntax for changing characters in strings

    Strings are immutable, so direct assignment like str.charAt(0) = 'A' is invalid.
  2. Step 2: Use substring to create a new string

    Concatenate "A" with the substring from index 1 to form a new string.
  3. Final Answer:

    str = "A" + str.substring(1); -> Option C
  4. Quick Check:

    Use substring + concat to change string [OK]
Hint: Use substring and concat to create new string [OK]
Common Mistakes:
  • Trying to assign directly to string characters
  • Using array-like indexing on strings
  • Using non-existent methods like replaceChar
3. What is the output of the following code?
String s = "hello";
s.toUpperCase();
System.out.println(s);
medium
A. HELLO
B. hello
C. null
D. HELLOhello

Solution

  1. Step 1: Understand that strings are immutable

    The method toUpperCase() returns a new string but does not change the original string s.
  2. Step 2: Check what is printed

    Since s was not reassigned, printing s outputs the original string "hello".
  3. Final Answer:

    hello -> Option B
  4. Quick Check:

    Original string unchanged = hello [OK]
Hint: toUpperCase returns new string; original stays same [OK]
Common Mistakes:
  • Assuming toUpperCase changes original string
  • Expecting uppercase output without reassignment
  • Confusing method effect with print output
4. Find the error in this code snippet:
String s = "test";
s.charAt(0) = 'T';
System.out.println(s);
medium
A. Cannot assign to charAt() result; strings are immutable.
B. Missing semicolon after declaration.
C. charAt() method does not exist for String.
D. System.out.println() cannot print strings.

Solution

  1. Step 1: Check usage of charAt()

    The method charAt() returns a character but cannot be assigned a new value.
  2. Step 2: Understand string immutability

    Strings cannot be changed by assigning to characters; this causes a compile error.
  3. Final Answer:

    Cannot assign to charAt() result; strings are immutable. -> Option A
  4. Quick Check:

    charAt() result is read-only [OK]
Hint: charAt() returns char, cannot assign to it [OK]
Common Mistakes:
  • Trying to assign to charAt()
  • Thinking strings are mutable
  • Ignoring compile errors on assignment
5. You want to replace all occurrences of the letter 'a' with 'b' in a string input. Which code correctly does this considering string immutability?
hard
A. input.replace('a', 'b'); System.out.println(input);
B. input.charAt(0) = 'b'; System.out.println(input);
C. input.toCharArray()[0] = 'b'; System.out.println(input);
D. input = input.replace('a', 'b'); System.out.println(input);

Solution

  1. Step 1: Understand replace() returns new string

    The replace() method returns a new string with replacements but does not change the original.
  2. Step 2: Assign the new string back to input

    To update input, assign the result of replace() back to it before printing.
  3. Final Answer:

    input = input.replace('a', 'b'); System.out.println(input); -> Option D
  4. Quick Check:

    Assign replace result to variable to update string [OK]
Hint: Assign replace() result to variable to update string [OK]
Common Mistakes:
  • Calling replace() without assignment
  • Trying to assign to charAt() or array elements
  • Expecting original string to change automatically
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard