Understanding Java String, StringBuilder, and StringBuffer
Java String Classes
Java has provide three different classes to handle strings.
- String class is — imutable
- StringBuilder and StringBuffer are - mutable
Which means once immutable objects are objects whose state (data) cannot be modified after the object is created while mutable objects are objects whose state (data) can be modified after the object is created.
Immutable objects may have higher memory overhead because each modification creates a new object.
Java String object
In Java, when you create instances of objects, memory allocation typically involves the String Pool and the heap.In String class uses String constant pool.Let’s break down the memory allocation for the provided code segment:
- First String Literal (
"Hello"):
- When the code encounters the string literal “Hello”, it is stored in the String Pool.
- If the literal already exists in the String Pool, the existing reference is reused. In this case, “Hello” is stored in the String Pool.
2. Reference Assignment (String str = ...):
String str = "Hello";: Declares aStringvariable namedstrand assigns it the reference to the string literal "Hello" in the String Pool.- The variable
strnow points to the memory location where the string literal "Hello" is stored.
3. Second String Literal ("Hello"):
- When the code encounters the string literal “Hello” again, it checks the String Pool.
- Since “Hello” is already present in the String Pool, the existing reference is reused. No new string object is created.
4. Reference Assignment (String strCopy = ...):
String strCopy = "Hello";: Declares anotherStringvariable namedstrCopyand assigns it the reference to the same string literal "Hello" in the String Pool.- The variable
strCopynow also points to the same memory location where the string literal "Hello" is stored.
5. Print Statements:
System.out.println(str);: Prints the value ofstrto the console. The value is "Hello".System.out.println(strCopy);: Prints the value ofstrCopyto the console. The value is also "Hello".
In summary:
- The string literal “Hello” is stored in the String Pool.
- Both
strandstrCopyreference the same string literal "Hello" in the String Pool.
The use of the String Pool allows Java to optimize memory usage by reusing existing string literals, promoting efficiency when working with string constants.
StringBuilder Class
In Java, the memory allocation for StringBuilder objects involves the heap. Let's break down the memory allocation for the provided code segment:
- First
StringBuilder(new StringBuilder("Hello")):
new StringBuilder("Hello"): Creates a newStringBuilderobject with the initial content "Hello".- The new
StringBuilderobject is allocated memory on the heap.
2.Reference Assignment (StringBuilder strBuilder = ...):
StringBuilder strBuilder = new StringBuilder("Hello");: Declares aStringBuildervariable namedstrBuilderand assigns it the reference to the newly createdStringBuilderobject.- The variable
strBuildernow points to the memory location where theStringBuilderobject with the content "Hello" is stored.
3. Second StringBuilder (new StringBuilder("Hello")):
new StringBuilder("Hello"): Creates another newStringBuilderobject with the same initial content "Hello".- This results in a separate
StringBuilderobject being allocated memory on the heap.
4. Reference Assignment (StringBuilder strBuilderCopy = ...):
StringBuilder strBuilderCopy = new StringBuilder("Hello");: Declares anotherStringBuildervariable namedstrBuilderCopyand assigns it the reference to the secondStringBuilderobject.- The variable
strBuilderCopynow points to the memory location where the secondStringBuilderobject with the content "Hello" is stored.
5. Print Statements:
System.out.println(strBuilder);: Prints the value ofstrBuilderto the console. The value is the string representation of theStringBuilderobject.System.out.println(strBuilderCopy);: Prints the value ofstrBuilderCopyto the console. The value is the string representation of the secondStringBuilderobject.
In summary:
- Two
StringBuilderobjects are created on the heap, each with the initial content "Hello". strBuilderandstrBuilderCopyare reference variables that point to the memory locations of their respectiveStringBuilderobjects.
Unlike String objects, StringBuilder objects are mutable, meaning you can modify their contents without creating new objects. The memory allocation for StringBuilder objects is dynamic, and the objects can be resized as needed.
StringBuffer Class
In Java, when you create instances of StringBuffer objects, memory allocation typically involves the heap. Let’s break down the memory allocation for the provided code segment:
- First
StringBuffer(new StringBuffer("Hello")):
new StringBuffer("Hello"): Creates a newStringBufferobject with the initial content "Hello".- The new
StringBufferobject is allocated memory on the heap.
2. Reference Assignment (StringBuffer strbuffer = ...):
StringBuffer strbuffer = new StringBuffer("Hello");: Declares aStringBuffervariable namedstrbufferand assigns it the reference to the newly createdStringBufferobject.- The variable
strbuffernow points to the memory location where theStringBufferobject with the content "Hello" is stored.
3. Second StringBuffer (new StringBuffer("Hello")):
new StringBuffer("Hello"): Creates another newStringBufferobject with the same initial content "Hello".- This results in a separate
StringBufferobject being allocated memory on the heap.
4. Reference Assignment (StringBuffer strbuffercopy = ...):
StringBuffer strbuffercopy = new StringBuffer("Hello");: Declares anotherStringBuffervariable namedstrbuffercopyand assigns it the reference to the secondStringBufferobject.- The variable
strbuffercopynow points to the memory location where the secondStringBufferobject with the content "Hello" is stored.
5. Print Statements:
System.out.println(strbuffer);: Prints the value ofstrbufferto the console. The value is the string representation of theStringBufferobject.System.out.println(strbuffercopy);: Prints the value ofstrbuffercopyto the console. The value is the string representation of the secondStringBufferobject.
In summary:
- Two
StringBufferobjects are created on the heap, each with the initial content "Hello". strbufferandstrbuffercopyare reference variables that point to the memory locations of their respectiveStringBufferobjects.
Unlike String objects, StringBuffer objects are mutable, meaning you can modify their contents without creating new objects. The memory allocation for StringBuffer objects is dynamic, and the objects can be resized as needed.
Immutability -Perfomance -Thread Safety
Memory Efficiency:
- Strings are memory-efficient but create new objects on each modification.
StringBuilderandStringBufferprovide more efficient memory usage for dynamic modifications.
In summary, the choice between String, StringBuilder, and StringBuffer depends on the specific requirements of your application, such as immutability, performance, and thread safety. Each class serves different use cases, so choosing the right one is essential for optimal functionality and efficiency.
Get BuddhiK’s stories in your inbox
Join Medium for free to get updates from this writer.
Look in to the below code segments and the outputs.
example for String class object :
Run below source code and see the results. Both str and strCopy point in to the same memory address.
example for StringBuilder class object :
Run below source code and see the results. Both strBuilder and strBuilderCopy point in to two different memory addresses.
example for StringBuffer class object :
Run below source code and see the results. Both str and strCopy point in to two different memory addresses.
'==’ Operator: The == operator in Java checks for reference equality, i.e., whether the two variables point to the same memory location.
String class
- The
==operator compares the references of twoStringobjects. It checks whether they refer to the same memory location. - Example:
StringBuilder
- The
==operator forStringBuildercompares the references of twoStringBuilderobjects, similar to theStringclass. - Example:
StringBuffer Class
- The
==operator forStringBuffercompares the references of twoStringBufferobjects, just like with other classes. - Example:
'equals' Method: The equals method checks both the content and the type of the objects.
String Class
- The
equalsmethod in theStringclass is overridden to compare the contents of two strings. - Example:
StringBuilder Class
- The
equalsmethod in theStringBuilderclass is not overridden to compare the contents of twoStringBuilderobjects. It uses reference equality. - Example:
StringBuffer Class
- The
equalsmethod in theStringBufferclass is not overridden to compare the contents of twoStringBufferobjects. It uses reference equality. - Example:
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -
- For
String, it's common to useequalsto compare the content, as the==operator compares references, not content. - For
StringBuilder,strinBuffer, you typically compare the contents indirectly by converting them to strings and then usingequals:
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
Compare across the classes
Example 01 :
String Vs StringBuffer
str.equals(buffer) Comparison:
- The
equalsmethod in theStringclass is overridden to compare the content of two strings. However, when comparing aStringwith aStringBuffer, they are considered not equal because their types are different. - The
equalsmethod checks both the content and the type of the objects. Sincestris aStringandbufferis aStringBuffer, the result ofstr.equals(buffer)isfalse. - Output is “Both are not equal”
You can use str.equals(buffer.toString()) to compair the content .
Example 02 :
StringBuilder Vs StringBuilder
Here s1==s2 checks whether the two variables point to the same memory location.Since s1 and s2 are two different StringBuilder objects and pointing to different memory location results is false.
s1.equals(s2) — equals method in the StringBuilder class is not overridden to compare the content of the StringBuilder objects.The default implementation of equals in the Object class checks for reference equality, so s1.equals(s2) will also evaluate to false.
Output — Nothing will print since the both if conditions are false.
Example 03 :
String Vs String
str1 == str2Comparison:
- The
==operator checks for reference equality. In this case, bothstr1andstr2are string literals, and Java often uses string pooling, which means that identical string literals share the same memory location. - Therefore,
str1 == str2will evaluate totruebecause they reference the same memory location.
2. str1.equals(str2) Comparison:
- The
equalsmethod in theStringclass is overridden to compare the content of the strings. Since both strings have the same content,str1.equals(str2)will also evaluate totrue.
Output:
- Both conditions are
true, so the following output will be printed:
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —
java.lang.String class provides many useful methods to perform operations on string values. Lets meet again with methods of strings in Java!









