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.
StringBuilder instead of String in Java?String and StringBuilderString objects are immutable, meaning they cannot be changed once created. Changing text creates new objects, which is slow and uses more memory.StringBuilder is betterStringBuilder allows changing text without creating new objects, making it efficient for many modifications.StringBuilder when you need to change text many times efficiently. -> Option AStringBuilder [OK]StringBuilder object with initial text "Hello"?StringBuilder class requires the new keyword and parentheses with the initial string inside.new StringBuilder("Hello"), which is correct. Options A, B, and D have syntax errors or wrong usage.StringBuilder sb = new StringBuilder("Hi");
sb.append("!");
sb.append(" How are you?");
System.out.println(sb.toString());append() adds the given text to the end of the current StringBuilder content without spaces unless explicitly added.StringBuilder sb = new StringBuilder("Test");
sb = sb + "ing";
System.out.println(sb);sb.append("ing") to add text instead of + operator.Option A:
String sentence = "";
for (String word : words) {
sentence += word + " ";
}
Option B:
StringBuilder sentence = new StringBuilder();
for (String word : words) {
sentence.append(word).append(" ");
}Pass the test and this pattern moves unknown