What is the difference between String and StringBuffer in Java?
In this shot, we will discuss the difference between the String and StringBuffer classes in Java.
The table below lists some of the differences in properties between String and StringBuffer.
Parameter | String | StringBuffer |
Storage | String pool | Heap memory |
Mutability | Immutable | Mutable |
Performance | Slower than StringBuffer while performing concatenation | Faster than String while performing concatenation |
Length | Fixed | Can be increased |
Usage in threaded environment | Not used in a threaded environment | Used in a multi-threaded environment |
Synchronization | Not synchronized | Synchronized |
Syntax | String variable=”String”; String variable= new String(“String”); | StringBuffer variable= new StringBuffer(“String”); |
Code
In the code below, we create objects of both the String and StringBuffer classes.
We perform concatenation on String instances with the += operator and concatenation on StringBuffer instances with the append() method.
class Main{public static void main(String[] args){String s = new String("This ");s += "is a ";s += "String object";System.out.println(s);StringBuffer sb = new StringBuffer("This ");sb.append("is a ");sb.append("StringBuffer object");System.out.println(sb);}}
Explanation
-
In line 1, we create the
Mainclass. -
In line 6, we initialize an instance of the
Stringclass and concatenate it with the other strings in lines and . Each time the code performs the+=operation, a newStringis created in theStringpool. -
In line 9, we display the concatenated
String. -
In line 11, we initialize an instance of the
StringBufferclass. TheStringBufferobject is altered twice, in lines and . Each time the code uses theappend()operation, no new object is created. -
In line 14, we display the concatenated
StringBufferobject.
In this way, we analyzed the difference between String and StringBuffer in Java. The StringBuffer class can be used to boost performance when you concatenate many strings together in a loop.