Concept Flow - String vs StringBuilder
Create String or StringBuilder
Modify content?
String: create new String
Use updated value
End
Shows how String creates new objects on change, while StringBuilder modifies content without new objects.
String s = "Hi"; s = s + "!"; StringBuilder sb = new StringBuilder("Hi"); sb.append("!"); System.out.println(s); System.out.println(sb.toString());
| Step | Variable | Action | Value After Action | Notes |
|---|---|---|---|---|
| 1 | s | Initialize with "Hi" | "Hi" | String s points to "Hi" |
| 2 | s | Concatenate "!" to s | "Hi!" | New String created, s points to "Hi!" |
| 3 | sb | Create StringBuilder with "Hi" | StringBuilder("Hi") | sb holds mutable sequence "Hi" |
| 4 | sb | Append "!" to sb | StringBuilder("Hi!") | sb content changed in place |
| 5 | s | Print s | "Hi!" | Outputs Hi! |
| 6 | sb | Print sb.toString() | "Hi!" | Outputs Hi! |
| 7 | - | End of program | - | Execution stops |
| Variable | Start | After Step 2 | After Step 4 | Final |
|---|---|---|---|---|
| s | "Hi" | "Hi!" | "Hi!" | "Hi!" |
| sb | null | null | StringBuilder("Hi!") | StringBuilder("Hi!") |
String vs StringBuilder in Java: - String is immutable; changes create new objects. - StringBuilder is mutable; changes happen in place. - Use StringBuilder for many modifications to improve performance. - String concatenation creates new Strings each time. - StringBuilder has append() method to add content efficiently.