Key Difference – String vs StringBuffer vs StringBuilder in Java
String, StringBuffer and String Builder are classes in Java. String is widely used in Java programming. Once an object of String is created, it is not possible to change them. Each time a change occurs to the String, it creates a new String. Even if it is a concatenation to an existing String it creates a new String. This causes memory wastage. StringBuffer and StringBuilder classes in Java are used to modify String. The key difference between String, StringBuffer and StringBuilder in Java is that String is a class to create an object of type String that is a sequence of characters, StringBuffer is a class that is used to modify Strings that provides thread safety, and StringBuilder is a class that is used to modify Strings that do not provide thread safety.
CONTENTS
1. Overview and Key Difference
2. What is String in Java
3. What is StringBuffer in Java
4. What is StringBuilder in Java
5. Similarities Between String StringBuffer and StringBuilder in Java
6. Side by Side Comparison – String vs StringBuffer vs StringBuilder in Java in Tabular Form
7. Summary
What is String in Java?
String class is in java.lang package. Each time the programmer creates a String, it is an object of type String. Strings are immutable meaning once the object is created, it cannot be changed. Objects created using wrapper classes such as Integer, Byte, Float, Double are also immutable. A string literal is enclosed in double quotes. e.g. “Hello World”. Each time a string literal created, the Java Virtual Machine (JVM) checks the String constant pool. If the String exists, a reference to the String constant pool is returned. If it is a new String, that object is created in the String constant pool.
Refer the below piece of code.
String s1= “Hello”;
s1 = s1 + “World”;
System.out.println(s1);
In the first statement, s1 is referring to the “Hello” in the String constant pool. In the second statement, JVM does not change the existing String. Instead, it creates a new String as “Hello World” and s1 is now referring to that new String. The exiting “Hello” object still exists in the String constant pool.
If there is a code which is,
String s1 =”Hello”;
String s2 = s1;
s1, s2 both will be referring to the String object “Hello”.