Difference between String and StringBuffer — Java Technical Interview Questions & Answers
Difference between String and StringBuffer
Difference between String and StringBuffer
- String is immutable: once created, the characters do not change. toUpperCase() returns a new String. The old one stays the same. That is why the String Pool can safely reuse literals.
- Immutability also helps security (passwords, class names) and hashing (a String used as a HashMap key cannot silently change).
- If you need to change text many times, use StringBuilder. Don’t fight String by concatenating in a loop.
- Let's take this on the board with one tiny Main class — no extra files. Difference between String and StringBuffer — same append idea as Builder, but synchronized. Start from main, go line by line, and stop at each print. That output is the proof for Difference between String and StringBuffer.
Technical Interview Tip: Buffer = thread-safe builder.
Code Examples for Difference between String and StringBuffer
Example
// StringBuffer demo
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hi");
sb.append(" Java");
System.out.println(sb);
}
}Difference between String and StringBuffer — same append idea as Builder, but synchronized.
How to Explain Difference between String and StringBuffer to an Interviewer
What is the difference in Difference between String and StringBuffer?
String is immutable. Methods return a new String. Pool can reuse literals because content never changes. Safer for HashMap keys and for security.
When do you pick each side?
Match the problem Don’t pick only what you revised last
Give one example of Difference between String and StringBuffer.
Show both sides Say the output
What mistake do beginners make?
Mixing both ideas Only memorising names
Where is Difference between String and StringBuffer used?
Real Java program