Builds a string by appending parts and prints the final combined string.
data_tableExecution Table
Step
Action
StringBuilder Content
Output
1
Create StringBuilder with "Hi"
"Hi"
2
Append " there"
"Hi there"
3
Append "!"
"Hi there!"
4
Convert to String and print
"Hi there!"
Hi there!
5
End of program
"Hi there!"
Program ends
💡 All append operations done; final string printed and program ends.
search_insightsVariable Tracker
Variable
Start
After Step 2
After Step 3
Final
sb
"Hi"
"Hi there"
"Hi there!"
"Hi there!"
keyKey Moments - 3 Insights
▶Why do we use StringBuilder instead of just adding strings with +?
▶What is the difference between StringBuilder and StringBuffer?
▶Why do we call toString() at the end?
psychologyVisual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the content of sb after step 2?
A"Hi there!"
B"Hi"
C"Hi there"
D" there"
photo_cameraConcept Snapshot
StringBuilder and StringBuffer create mutable strings.
Use append() to add text efficiently.
StringBuilder is faster but not thread-safe.
StringBuffer is thread-safe but slower.
Call toString() to get final String.
Ideal for many string changes.
contractFull Transcript
This visual trace shows how StringBuilder works in Java. First, we create a StringBuilder with initial content "Hi". Then we append " there" and "!" step by step, changing the content without making new string objects each time. Finally, we convert the StringBuilder to a String using toString() and print it. This is faster than using + to join strings repeatedly. StringBuffer works similarly but is safe for multiple threads. Remember that println implicitly calls toString() to get the string content for output. This example helps beginners see how mutable strings work and why StringBuilder is useful.