java 39 | StringBuffer and StringBuilder class | mutable string

preview_player
Показать описание
Java StringBuffer class is used to create mutable (modifiable) string.
The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.
At the end of this class students will be able to : -
Use StringBuffer class
Use StringBuilder class
Apply reverse( ) method to reverse the strings.

StringBuffer and StringBuilder classes are used for creating mutable string.
The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters.
Unlike Strings, objects of type StringBuffer and String builder can be modified over and over again without leaving behind a lot of new unused objects.

The append() method concatenates the given argument with this string.
class StringBufferExample{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello ");  
}  
}  

The reverse() method of StringBuffer class reverses the current string.
class StringBufferExample{  
public static void main(String args[]){  
StringBuffer sb=new StringBuffer("Hello");  
}  
}  

StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.
StringBuffer is less efficient than StringBuilder.
StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously
StringBuilder is more efficient than StringBuffer.
Both StringBuffer and StringBuilder have the same methods (besides synchronized method declaration in the StringBuffer class).
Let's go through some of the most common ones:
append()
insert()
replace()
delete()
reverse()
Рекомендации по теме