Understanding Java String, StringBuilder, and StringBuffer
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 aString
variable namedstr
and assigns it the reference to the string literal "Hello" in the String Pool.- The variable
str
now 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 anotherString
variable namedstrCopy
and assigns it the reference to the same string literal "Hello" in the String Pool.- The variable
strCopy
now also points to the same memory location where the string literal "Hello" is stored.
5. Print Statements:
System.out.println(str);
: Prints the value ofstr
to the console. The value is "Hello".System.out.println(strCopy);
: Prints the value ofstrCopy
to the console. The value is also "Hello".
In summary:
- The string literal “Hello” is stored in the String Pool.
- Both
str
andstrCopy
reference 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 newStringBuilder
object with the initial content "Hello".- The new
StringBuilder
object is allocated memory on the heap.
2.Reference Assignment (StringBuilder strBuilder = ...
):
StringBuilder strBuilder = new StringBuilder("Hello");
: Declares aStringBuilder
variable namedstrBuilder
and assigns it the reference to the newly createdStringBuilder
object.- The variable
strBuilder
now points to the memory location where theStringBuilder
object with the content "Hello" is stored.
3. Second StringBuilder
(new StringBuilder("Hello")
):
new StringBuilder("Hello")
: Creates another newStringBuilder
object with the same initial content "Hello".- This results in a separate
StringBuilder
object being allocated memory on the heap.
4. Reference Assignment (StringBuilder strBuilderCopy = ...
):
StringBuilder strBuilderCopy = new StringBuilder("Hello");
: Declares anotherStringBuilder
variable namedstrBuilderCopy
and assigns it the reference to the secondStringBuilder
object.- The variable
strBuilderCopy
now points to the memory location where the secondStringBuilder
object with the content "Hello" is stored.
5. Print Statements:
System.out.println(strBuilder);
: Prints the value ofstrBuilder
to the console. The value is the string representation of theStringBuilder
object.System.out.println(strBuilderCopy);
: Prints the value ofstrBuilderCopy
to the console. The value is the string representation of the secondStringBuilder
object.
In summary:
- Two
StringBuilder
objects are created on the heap, each with the initial content "Hello". strBuilder
andstrBuilderCopy
are reference variables that point to the memory locations of their respectiveStringBuilder
objects.
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 newStringBuffer
object with the initial content "Hello".- The new
StringBuffer
object is allocated memory on the heap.
2. Reference Assignment (StringBuffer strbuffer = ...
):
StringBuffer strbuffer = new StringBuffer("Hello");
: Declares aStringBuffer
variable namedstrbuffer
and assigns it the reference to the newly createdStringBuffer
object.- The variable
strbuffer
now points to the memory location where theStringBuffer
object with the content "Hello" is stored.
3. Second StringBuffer
(new StringBuffer("Hello")
):
new StringBuffer("Hello")
: Creates another newStringBuffer
object with the same initial content "Hello".- This results in a separate
StringBuffer
object being allocated memory on the heap.
4. Reference Assignment (StringBuffer strbuffercopy = ...
):
StringBuffer strbuffercopy = new StringBuffer("Hello");
: Declares anotherStringBuffer
variable namedstrbuffercopy
and assigns it the reference to the secondStringBuffer
object.- The variable
strbuffercopy
now points to the memory location where the secondStringBuffer
object with the content "Hello" is stored.
5. Print Statements:
System.out.println(strbuffer);
: Prints the value ofstrbuffer
to the console. The value is the string representation of theStringBuffer
object.System.out.println(strbuffercopy);
: Prints the value ofstrbuffercopy
to the console. The value is the string representation of the secondStringBuffer
object.
In summary:
- Two
StringBuffer
objects are created on the heap, each with the initial content "Hello". strbuffer
andstrbuffercopy
are reference variables that point to the memory locations of their respectiveStringBuffer
objects.
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.
StringBuilder
andStringBuffer
provide 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.
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 twoString
objects. It checks whether they refer to the same memory location. - Example:
StringBuilder
- The
==
operator forStringBuilder
compares the references of twoStringBuilder
objects, similar to theString
class. - Example:
StringBuffer Class
- The
==
operator forStringBuffer
compares the references of twoStringBuffer
objects, just like with other classes. - Example:
'equals'
Method: The equals
method checks both the content and the type of the objects.
String Class
- The
equals
method in theString
class is overridden to compare the contents of two strings. - Example:
StringBuilder Class
- The
equals
method in theStringBuilder
class is not overridden to compare the contents of twoStringBuilder
objects. It uses reference equality. - Example:
StringBuffer Class
- The
equals
method in theStringBuffer
class is not overridden to compare the contents of twoStringBuffer
objects. It uses reference equality. - Example:
— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -
- For
String
, it's common to useequals
to 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
equals
method in theString
class is overridden to compare the content of two strings. However, when comparing aString
with aStringBuffer
, they are considered not equal because their types are different. - The
equals
method checks both the content and the type of the objects. Sincestr
is aString
andbuffer
is 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 == str2
Comparison:
- The
==
operator checks for reference equality. In this case, bothstr1
andstr2
are string literals, and Java often uses string pooling, which means that identical string literals share the same memory location. - Therefore,
str1 == str2
will evaluate totrue
because they reference the same memory location.
2. str1.equals(str2)
Comparison:
- The
equals
method in theString
class 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!