Monday 30 March 2020

Difference between String, String Builder and String Buffer

Immutable : Cannot change value
Mutable : Can change the Value


String :

 String is Immutable.
 If we update any existing String then it will create String object. It won't override existing value.

Ex : 
String S1="Testing"
print (S1)

String concat(String s1){
S1 = S1+"Java"
}

O/P

S1: Testing


String Builder

String Builder is mutable.
we can change value. if any thing update then it will override existing object itself.

Ex : 
StringBuilder S1="Testing"
print (S1)

String concat(String s1){
S1 = S1.append("Java")
}

O/P

S1: Testing Java


String Buffer

Both String Buffer and String builder same. Except one concept.
String Buffer is thread safe. we can refer the String buffer object via multi thread.

String Buffer is mutable. we can change value. if any thing update then it will override existing object itself.

Ex : 
StringBuffer S1="Testing"
print (S1)

String concat(String s1){
S1 = S1.append("Java")
}

O/P

S1 : Testing Java





When to use

String : if String object value contant entire program.
String Builder : If String object value need to change at any time.
String Buffer : If String object value need to change at any time. It can be access same value via multithread.

No comments:

Post a Comment