It is one of the most popular interview question.
1.String is immutable (once created can not be changed )object.
String test= "Hi" ; // The above object is stored in constant string pool and its value can not be modified. test="Bye" ; //new "Bye" string is created in constant pool and referenced by the demo variable // "Hi" string still exists in string constant pool and its value is not overrided but we lost reference to the "hello"string
2.immutable object in Java is thread safe ,that means String is also thread safe. String can not be used by two threads simultaneously.
1.StringBuffer is mutable(one can change the value of the object)
2.Both StringBuffer and StringBuilder have same methods but methods in StringBuffer are synchronized.
3.Since StringBuffer is synchronized it is thread safe .
1.StringBuffer is is mutable(one can change the value of the object).
2.Both StringBuffer and StringBuilder have same methods but methods in StringBuilder are not synchronized.
3.Since StringBuilder is not synchronized it is not thread safe .
Note:Use String if you need immutability, use StringBuffer if you need mutable + thread-safety and use StringBuilder if you need mutable + without thread-safety.