Apart from String
class java has given two more classes to handle string values in java, StringBuffer
and
StringBuilder
. These classes were added with some purpose, this tutorial explains
the purpose to add these classes, the difference between both and when to use StringBuffer or StringBuilder.
String in java is immutable, which means you can not change string value once created. Whenever we do string manipulation
like concatenation, substring, replace etc, it generates a new string and leaves the original string as it is in memory which becomes a garbage value. For an example the code given below will
generate a garbage value as "refresh java"
in memory.
String str ="refresh java"
; str = str +" tutorial"
;
The concatenation operation above will create a new strings as "refresh java tutorial"
in string pool memory and assigns it's reference in str
but this operation won't change the original string "refresh java"
,
it will still exist in pool memory as a garbage value.
what is garbage value ?
Any value or object inside the memory that is not being referred by program or application is known as garbage. The process of collecting and destroying such values from memory is known as garbage collection.
The string manipulation operations doesn't cost much if it is not happening frequently, but if it's happening frequently and at many number of places in your application, this may cause serious memory leak and performance issue as it will generate a lot of garbage in memory. To solve this problem java designer has given two more classes, StringBuffer and StringBuilder.
The string values stored in StringBuffer or StringBuilder data type are mutable. In other words objects of StringBuffer and StringBuilder classes are mutable which means if you apply any operation on such strings, it will change the original string itself rather than creating a new string. As a result it will not generate garbage in memory. The Syntax of declaring StringBuffer and StringBuilder is :
StringBuffer var_name =new
StringBuffer("StringBuffer value"
); StringBuilder var_name =new
StringBuilder("StringBuilder value"
);// Example
StringBuffer strbuff =new
StringBuffer("refresh java"
); StringBuilder strbdr =new
StringBuilder("java is easy"
);
Here StringBuffer
and StringBuilder
are the data type(classes), var_name
is the name of variable given
as per the programmers choice and the value of variable is given inside ""
.
Java considers string literal(value given in ""
) as String
type, so you can not assign string literal directly to
StringBuffer and StringBuilder variable as given below. You must have to use new
keyword to create StringBuffer and StringBuilder.
// Both line will throw compilation error.
StringBuffer strbuff ="refresh java"
; StringBuilder strbdr ="java is easy"
;
You can also not use + operator to concat string on StringBuffer and StringBuilder variables.
StringBuffer strbuff =new
StringBuffer("refresh java"
); StringBuilder strbdr =new
StringBuilder("java is easy"
);// Both line will throw compilation error.
strbuff = strbuff +" another value"
; strbdr = strbdr +" another value"
;
How can I add another string value in StringBuffer or StringBuilder variable ?
You need to use append() method of these classes to add another string. Refer the program given below to see the use of this method.
StringBuffer and StringBuilder program in Java
class
StringBufferAndBuilder {public static void
main(String args[]) { String str ="refresh java"
; String str2 = str; StringBuffer strbuff =new
StringBuffer("StringBuffer on refresh java"
); StringBuffer strbuff2 = strbuff; StringBuilder strbuild =new
StringBuilder("StringBuilder on refresh java"
); StringBuilder strbuild2 = strbuild; str = str +" tutorial"
; strbuff = strbuff.append(" tutorial"
); strbuild = strbuild.append(" tutorial"
); System.out.println("str = "
+str); System.out.println("str2 = "
+str2); System.out.println("strbuff = "
+strbuff); System.out.println("strbuff2 = "
+strbuff2); System.out.println("strbuild = "
+strbuild); System.out.println("strbuild2 = "
+strbuild2); } }
Output:
str = refresh java tutorial
str2 = refresh java
strbuff = StringBuffer on refresh java tutorial
strbuff2 = StringBuffer on refresh java tutorial
strbuild = StringBuilder on refresh java tutorial
strbuild2 = StringBuilder on refresh java tutorial
As you can see in the output, both String
variable have different value while both the StringBuffer
and
StringBuilder
variable have same value, that's because String
is immutable. Once you
add a string literal in String
variable, java creates a new string object and assigns the reference of it in String
variable while in-case
of StringBuffer and StringBuilder, the same string is modified.
Useful StringBuilder and StringBuffer methods in Java
Table below shows some of the useful methods of StringBuffer and StringBuilder class which is commonly used for string manipulation. Both the classes have
same methods, the only difference is that methods of StringBuffer class is synchronized
. Below table assumes we have a variable s1
of type
StringBuffer
.
Name | Description | Example |
---|---|---|
append(String str) | It appends the string represented by str at the end of given string. |
s1 = new StringBuffer("refresh" );s1.append( "Java" ); // s1 = "refreshJava" |
insert(int offset, String str) |
Used to insert string represented by str at index specified by offset in given string. |
s1 = new StringBuffer("refresh" );s1.insert(2, "java" ); // s1 = "rejavafresh" |
delete (int startIndex, int endIndex) |
It deletes characters from startIndex to (endIndex-1) from given string. |
s1 = new StringBuffer("refresh java" );s1.delete(2,7); // s1 = "re java" |
replace (int start, int end, String str) |
It replaces characters from start to (end-1) index with string represented by str in given string. |
s1 = new StringBuffer("refresh java" );s1.replace(0,7, "tutorial" ); // s1 = "tutorial java" |
reverse() | It reverses the sequence of characters of given string. | s1 = new StringBuffer("refresh java" );s1.reverse(); // s1 = "avaj hserfer" |
setCharAt(int index, char ch) |
Used to replace the character at given index with character represented by ch in given string. |
s1 = new StringBuffer("refresh" );s1.setCharAt(0, 's' ); // s1 = "sefresh" |
Conversion from String to StringBuffer/StringBuilder and vice-versa
You can not directly assign a String variable in StringBuffer/StringBuilder or vice-versa. You need to use conversion like below to store it in other string data type variable.
String str ="refresh java"
;// Both line will throw compilation error.
// StringBuffer strbuff = str; // StringBuilder strbdr = str;// Conversion from String to StringBuffer and StringBuilder.
StringBuffer strbuff =new
StringBuffer(str); StringBuilder strbdr =new
StringBuilder(str);// Both line will throw compilation error.
// String str2 = strbuff; // String str3 = strbdr;// Conversion from StringBuffer/StringBuilder to String.
String str2 = strbuff.toString(); String str3 = strbdr.toString();
String vs StringBuffer vs StringBuilder
- The String object is
immutable
while objects of StringBuffer and StringBuilder aremutable
. - StringBuffer is
thread safe
as it's methods aresynchronized
while StringBuilder is not, so use StringBuffer in multi-threaded environment where thread safety is needed. - StringBuffer is
not as faster as
StringBuilder for string manipulation operations, since methods of StringBuffer class is synchronized. - StringBuilder was added in
java 1.5
, before that there was only String and StringBuffer classes for string handling. - In single threaded environment, prefer String over StringBuilder if you don't need mutable objects as String is more easy and convenient to use. Use StringBuilder if mutable objects needed.
What is multi-thread environment ?
In a multi-threaded environment multiple programs or different parts(thread) of a program runs simultaneously.
What is synchronized in java ?
synchronized
is a keyword in java, use to achieve thread safety. A synchronized
method can not be accessed simultaneously by
multiple threads.
In most of the scenarios we don't use String data type in multithreaded environment where thread safety is needed, as it may cause inconsistent behavior. For example if a thread makes any changes in String variable, the other thread may not get the updated value which may cause inconsistent behavior of your program. To avoid such type of problem you should use StringBuffer class where thread safety is needed.
- Refer java oracle docs or java source code of StringBuffer and StringBuilder class to get details of all methods.
- There are many methods in String and StringBuffer/StringBuilder classes that are available in each other but not all.
- Digits can also be stored as string in StringBuffer and StringBuilder class in java, for example StringBuffer str = new StringBuffer("12345"); is a valid string.
- The '+' operator, which performs addition on primitives (such as int and double), is overloaded to perform concatenation on String objects. The compiler, internally uses the append method of StringBuffer/StringBuilder class to implement string concatenation.