String:
String is
immutable (once create not be changed) object. The object created as a String
is stored in “Constant String Pool”. Every immutable object in java is thread
safe, so String is also thread safe. String can not be used by two threads
simultaneously, String once assigned can not be changed.
String Demo = “hello”;
//The above object is store in constant string pool and it
value can not be modified.
Demo =”bye”;
//new ”bye” string is created in constant string pool and
its value is not override but we lost reference to the “hello” string.
String buffer:
String
buffer is mutable one can change the value of object, it will stored in heap,
each method in string buffer is synchronized that is string buffer is thread
safe, due to this it doesn’t allow two thread simultaneously access the same
method. Each method can be accessed by one thread at a time.
String Buffer can be converted to string by using toString()
method.
StringBuffer Demo1 = new StringBuffer(“hello”);
// The above object stored in heap area and it value can be
changed.
Demo1 = new StringBuffer(“bye”);
//The above statement is right as it modifies the value
which is allowed in the string buffer.
String builder:
String builder is same as string buffer, that is stores the
in the heap and it can also modified. String builder is not thread safe string
builder is fast as it is not thread safe.
StringBuilder Demo2 = new StringBuilder(“hello”);
// The above object stored in heap area and it value can be
modified.
Demo2 = new StringBuider(“bye”);
//The above statement is right as it modifies the value
which is allowed in the string builder.
|
|
String
|
String buffer
|
String builder
|
|
Storage area
|
Constant String Pool
|
Heap
|
Heap
|
|
Modifiable
|
No(immutable)
|
Yes(mutable)
|
Yes(mutable)
|
|
Thread safe
|
Yes
|
Yes
|
No
|
|
Performance
|
Fast
|
Very slow
|
Fast
|