Difference between String, StringBuffer and StringBuilder in Java - Java Interview Question
[a] based on => mutability difference
String => immutable [if you try to alter their value, another object gets created]
StringBuffer, StringBuilder => mutable
[b] based on => thread safety difference
StringBuffer
- thread safe [synchronized]
- it means: two/more threads can't call the methods of StringBuffer simultaneously
- less efficient
StringBuilder
- not thread safe [non-synchronized]
- it means two/more threads can call the methods of StringBuilder simultaneously
- more efficient/faster
Situations to use:
- if your string is not going to change - use String
- if your string can change & will only be accessed from a single thread - use StringBuilder
- if your string can change & can be accessed from multiple threads- use StringBuffer