Difference Between String vs StringBuffer
In JAVA, both String and StringBuffer classes are used to work with strings and are present in java.lang package. The major difference between String vs StringBuffer is:
String is Immutable: Once you create an object of String you cannot change it. Every modification on the string creates a new String object and discards the older one which creates lots of temporary garbage in the heap.
StringBuffer is Mutable: Object of StringBuffer is mutable i.e. performing modifications on the string using StringBuffer will not create new objects in the memory but it will update the content of string in an existing object.
Head to Head Comparison Between String vs StringBuffer (Infographics)
Below are the top 7 differences between String vs StringBuffer:
Key Differences Between String vs StringBuffer
let us discuss some of the major Difference Between String vs StringBuffer:
- If we perform any operations on a string using String class, it results in creating an entire string in the memory repeatedly whereas StringBuffer occupies some buffer space and modifies string value in that buffer space in the memory.
- Internal Working of String Class
String str = new String("Everything ");
Str.concat("is ");
Str.concat("learnable");
- Internal Working of StringBuffer Class
StringBuffer sb = new StringBuffer(“Everything ”);
sb.append(“is ”);
sb.append(“learnable”);
2. In the case of heavy string manipulations and a large number of string concatenations, StringBuffer provides better performance as compared to String.
Code:
import java.util.*;
public class Main
{
public static String StringConcat()
{
String str = "Hello";
for (int i = 0; i < 1000; i++)
{
str = str + "World";
}
return str;
}
public static String StringBufferConcat()
{
StringBuffer stringBuffer = new StringBuffer("Hello");
for (int i = 0; i < 1000; i++)
{
stringBuffer.append("World");
}
return stringBuffer.toString();
}
public static void main(String args[])
{
long time= System.currentTimeMillis();
StringConcat();
System.out.println("Time taken for String Concatenation: " + (System.currentTimeMillis()
- time) + "ms");
time = System.currentTimeMillis();
StringBufferConcat();
System.out.println("Time taken for StringBuffer Concatenation: " + (System.currentTimeMillis()
- time) + "ms");
}
}
Output:
3. As String class creates lots of string garbage in the memory after performing any operation on a string, it requires more memory as compared to StringBuffer.
4. If multiple string concatenations or heavy operations are required to perform on the string then StringBuffer should be used whereas if the content of the string is not going to change throughout the program then the String class should be used to work with strings in a thread-safe manner.
4.6 (3,144 ratings)
View Course
5. If a very less number of string concatenations are required then the String class is efficient and works faster than StringBuffer because adding characters in buffer space and then converting the whole content to string again, creates overhead for StringBuffer. Thus, in this case, StringBuffer works slower as compared to copy by value nature of String class.
6. String class overrides equals() and hashCode() methods of the Object class whereas StringBuffer does not override equals() and hashCode() methods of Object class.
Code:
import java.util.*;
public class Main
{
public static void main(String args[])
{
System.out.println("Performing hash code test on String:");
String str = "Everything";
System.out.println("Hash code value of 'Everything': " + str.hashCode());
str = str + "is";
System.out.println("Hash code value of 'is': " + str.hashCode());
str = str + "learnable";
System.out.println("Hash code value of 'learnable': " + str.hashCode());
System.out.println("");
System.out.println("Performing hash code test on StringBuffer:");
StringBuffer stringBuffer = new StringBuffer("Everything");
System.out.println("Hash code value of 'Everything': " + stringBuffer.hashCode());
stringBuffer.append("is");
System.out.println("Hash code value of 'is': " + stringBuffer.hashCode());
stringBuffer.append("learnable");
System.out.println("Hash code value of 'learnable': " + stringBuffer.hashCode());
}
}
Output:
In the above output, we can see that String returns different hash code values for different strings whereas StringBuffer returns the same hash code values for all strings. This proves that String class overrides hashCode() method of Object class.
7. String literals are stored in constant string pool whereas StringBuffer objects are stored in heap.
8. The object of String class is of fixed length and read-only in nature whereas the length of an object of StringBuffer can be increased when required and dynamic in nature.
9. String class supports interning i.e. strings with the same content share the same memory location whereas StringBuffer does not support interning.
Code:
import java.util.*;
public class Main
{
public static void main(String[] args) throws Exception
{
String str1 = "hello";
String str2 = "hello";
System.out.println(str1 == str2); //returns true
String str3 = str1.intern();
System.out.println(str1 == str3); //returns true
}
}
Output:
10. We can convert the String object to the StringBuffer object by passing the String object to the StringBuffer class constructor whereas to convert StringBuffer object to String object, we need to call toString() method.
Example:
String str = “abc”;
StringBuffer stringBuffer = new StringBuffer(str);
StringBuffer stringBuffer = new StringBuffer(“abc”);
String str = stringBuffer.toString();
Comparison Table of String and StringBuffer
Let’s us see the topmost comparison between String vs StringBuffer:
Parameter | String | StringBuffer |
Modifiable | The object of the String class isn’t modifiable. | The object of the StringBuffer class is modifiable. |
Performance | Slower than StringBuffer class for a large number of string concatenations. | Faster than String class for a large number of string concatenations. |
Storage Area | String literals are stored in a constant string pool. | StringBuffer objects are Stored in heap. |
Memory Requirement | It consumes more memory than StringBuffer. | It consumes less memory than String. |
Behavior of object | An object of String class is of fixed length i.e. read-only in nature. | The length of the StringBuffer object can be increased when required i.e. dynamic in nature. |
Efficiency | Less efficient than StringBuffer in case of concatenating many strings together in a loop. | More efficient than String in case of concatenating many strings together in a loop. |
Overriding equals() and hashCode() methods | String class overrides equals() and hashCode() methods of Object class. | StringBuffer does not override equals() and hashCode() methods of Object class. |
Conclusion
In JAVA, both String and StringBuffer classes are used to represent a sequence of characters. If the operations performed on a string do not change its value then the String class does not create a new object for the string. A new object is created when the value of string changes.
Recommended Articles
This is a guide to String vs StringBuffer. Here we discuss the String vs StringBuffer key differences with infographics and comparison table. You may also have a look at the following articles to learn more –