String vs StringBuffer vs StringBuilder in Java? Example (original) (raw)
Difference between String, StringBuffer, and StringBuilder
The String is one of the most important classes in Java and anyone who starts with Java programming uses String to print something on the console by using famous System.out.println() statements. Many Java beginners are not aware that String is immutable and final in Java and every modification in String creates a new String object. For example, when you get the substring, you get a new String, when you convert uppercase String to lowercase, a new String is created. Even when you remove space by calling the trim() method, a new String is returned.
So, now the big question is how do you manipulate String in Java without creating String garbage? StringBuilder and StringBuffer are the answer to this question. StringBuffer is an old class but StringBuilder is newly added in Java 5 along with major improvements in Enum, Generics, varargs methods, and Autoboxing in Java.
No matter which kind of application you are working you will find the heavy usage of the Java String class but if you do profiling of your application you will find that String is the one class that creates lots of garbage because of much temporary String created in the program.
In this Java tutorial we will see What is String in Java, some important properties of String in Java, What is StringBuffer in Java, When to use StringBuffer in Java, StringBuilder in Java, and how it can be used in place of StringBuffer, What are differences between String and StringBuffer and StringBuilder in Java which is also a frequently asked core Java question and mostly String vs StringBuilder vs StringBuffer.
Now let's start with String.
Differences between String, StringBuffer, and StringBuilder in Java
Before looking difference between String and StringBuffer or StringBuilder let’s see some fundamental properties of String Class in Java
1. Immutable
The string is immutable in Java: String is by design immutable in Java you can check this post for a reason. Immutability offers a lot of benefits to the String class e.g. his hashcode value can be cached which makes it a faster HashMap key and one of the reasons why String is a popular key in HashMap. Because String is final it can be safely shared between multiple threads without any extra synchronization.
2. String literal
When we represent a string in double quotes like "abcd" they are referred as String literal and String literals are created in String pools. When you compare two String literals using equality operator "==" it returns true because they are the actual same instance of String. Anyway comparing an object with an equality operator is bad practice in Java and you should always use the equals method to check equality.
3. String concatenation
The "+" operator is overloaded for String and used to concatenated two string. Internally "+" operation is implemented using either StringBuffer or StringBuilder. See thse Core Java books for more details on String concatenation in Java.
4. Character array
Strings are backed up by character Array and represented in UTF-16 format. By the way, this behavior can cause a memory leak in String because the same character array is shared between source String and SubString which can prevent source String from being garbage collected. See How SubString works in Java for more details.
5. Equality check
String class overrides equals() and hashcode() method and two Strings are considered to be equal if they contain exactly the same character in the same order and in the same case. If you want to ignore the case comparison of two strings consider using the equalsIgnoreCase() method. See how to correctly override the equals method in Java to learn more about best practices on the equals method.
Another worth noting point is that the equals method must be consistent with the compareTo() method for String because SortedSet and SortedMap e.g. TreeMap use the compareTo method to compare String in Java.
7. Representation
The toString() method provides String representation of any object and it's declared in Object class and it's recommended for other class to implement this and provide String representation.
8. The string is represented using the UTF-16 format in Java.
9. In Java, you can create String from a char array, byte array, another string, from StringBuffer, or from StringBuilder. Java String class provides a constructor for all of these.
10. Even though all StringBuffer, StringBuilder, and String are from the same type hierarchy i.e. they extend from the CharSequence interface, you cannot cast StringBuilder to StringBuffer or StringBuilder to String in Java. It will throw java.lang.ClasscastException, if you tried to cast even StringBuffer to String in Java.
Here is a nice diagram that shows the relationship between StringBuffer, StringBuilder, and String in Java:
Problem with String in Java
One of its biggest strengths Immutability is also the biggest problem of Java String if not used correctly. Many times we create a String and then perform a lot of operations on them e.g. converting a string into uppercase, lowercase, getting substring out of it, concatenating with other strings, etc.
Since String is an immutable class every time a new String is created and the older one is discarded which creates lots of temporary garbage in the heap.
If String is created using String literal they remain in the String pool. To resolve this problem Java provides us, two Classes, StringBuffer and StringBuilder. String Buffer is an older class but StringBuilder is relatively new and added in JDK 5.
Differences between String and StringBuffer in Java
The main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java.
You can convert a StringBuffer into String by its toString() method. String vs StringBuffer or what is the difference between StringBuffer and String is one of the popular Java interview questions for either phone interview or first round. Nowadays they also include StringBuilder and ask String vs StringBuffer vs StringBuilder.
So be prepared for that. In the next section, we will see the difference between StringBuffer and StringBuilder in Java. If you are preparing for Java interviews, then you can also check the Java Programming Interview exposed book for more such questions, one of the best books, which covers all important topics for Java interviews.
Difference between StringBuilder and StringBuffer in Java
StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided a similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of the cases than the StringBuffer class.
You can also use "+" for concatenating two strings because the "+" operation is internally implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java.
On the other hand, String vs StringBuffer is completely different and their API is also completely different, the same is true for StringBuilder vs String. Here is a nice summary of the difference between StringBuffer and StringBuilder in Java:
Summary
In summary here is a list of differences between StringBuffer, String, and StringBuilder in Java :
1. The String object is immutable in Java but StringBuffer and StringBuilder are mutable objects.
2. StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.
3. Concatenation operator "+" is internally implemented using either StringBuffer or StringBuilder.
4. Use String if you require immutability, use StringBuffer in java if you need mutable + thread-safety, and use StringBuilder in Java if you require mutable + without thread-safety.
That's all on famous String vs StringBuffer or StringBuffer vs StringBuilder discussion. All these differences help to avoid the common coding mistake of using String in place of StringBuffer in many places. from Java 5 onwards either use + operator of StringBuilder for concatenating String in Java.
Other Java String tutorials from Javarevisited Blog