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:

img 01
  1. 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 a String variable named str 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 another String variable named strCopy 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 of str to the console. The value is "Hello".
  • System.out.println(strCopy);: Prints the value of strCopy to the console. The value is also "Hello".

In summary:

  • The string literal “Hello” is stored in the String Pool.
  • Both str and strCopy 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:

img 02
  1. First StringBuilder (new StringBuilder("Hello")):
  • new StringBuilder("Hello"): Creates a new StringBuilder 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 a StringBuilder variable named strBuilder and assigns it the reference to the newly created StringBuilder object.
  • The variable strBuilder now points to the memory location where the StringBuilder object with the content "Hello" is stored.

3. Second StringBuilder (new StringBuilder("Hello")):

  • new StringBuilder("Hello"): Creates another new StringBuilder 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 another StringBuilder variable named strBuilderCopy and assigns it the reference to the second StringBuilder object.
  • The variable strBuilderCopy now points to the memory location where the second StringBuilder object with the content "Hello" is stored.

5. Print Statements:

  • System.out.println(strBuilder);: Prints the value of strBuilder to the console. The value is the string representation of the StringBuilder object.
  • System.out.println(strBuilderCopy);: Prints the value of strBuilderCopy to the console. The value is the string representation of the second StringBuilder object.

In summary:

  • Two StringBuilder objects are created on the heap, each with the initial content "Hello".
  • strBuilder and strBuilderCopy are reference variables that point to the memory locations of their respective StringBuilder 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:

img 03
  1. First StringBuffer (new StringBuffer("Hello")):
  • new StringBuffer("Hello"): Creates a new StringBuffer 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 a StringBuffer variable named strbuffer and assigns it the reference to the newly created StringBuffer object.
  • The variable strbuffer now points to the memory location where the StringBuffer object with the content "Hello" is stored.

3. Second StringBuffer (new StringBuffer("Hello")):

  • new StringBuffer("Hello"): Creates another new StringBuffer 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 another StringBuffer variable named strbuffercopy and assigns it the reference to the second StringBuffer object.
  • The variable strbuffercopy now points to the memory location where the second StringBuffer object with the content "Hello" is stored.

5. Print Statements:

  • System.out.println(strbuffer);: Prints the value of strbuffer to the console. The value is the string representation of the StringBuffer object.
  • System.out.println(strbuffercopy);: Prints the value of strbuffercopy to the console. The value is the string representation of the second StringBuffer object.

In summary:

  • Two StringBuffer objects are created on the heap, each with the initial content "Hello".
  • strbuffer and strbuffercopy are reference variables that point to the memory locations of their respective StringBuffer 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

img 04

Memory Efficiency:

  • Strings are memory-efficient but create new objects on each modification.
  • StringBuilder and StringBuffer 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.

img 05
img 06

example for StringBuilder class object :

Run below source code and see the results. Both strBuilder and strBuilderCopy point in to two different memory addresses.

img 07
img 08

example for StringBuffer class object :

Run below source code and see the results. Both str and strCopy point in to two different memory addresses.

img 09
img 10

'==’ 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 two String objects. It checks whether they refer to the same memory location.
  • Example:
img 11

StringBuilder

  • The == operator for StringBuilder compares the references of two StringBuilder objects, similar to the String class.
  • Example:
img 12

StringBuffer Class

  • The == operator for StringBuffer compares the references of two StringBuffer objects, just like with other classes.
  • Example:
img 13

'equals' Method: The equals method checks both the content and the type of the objects.

String Class

  • The equals method in the String class is overridden to compare the contents of two strings.
  • Example:
img 14

StringBuilder Class

  • The equals method in the StringBuilder class is not overridden to compare the contents of two StringBuilder objects. It uses reference equality.
  • Example:
img 15

StringBuffer Class

  • The equals method in the StringBuffer class is not overridden to compare the contents of two StringBuffer objects. It uses reference equality.
  • Example:
img 16

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — -

  • For String, it's common to use equals 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 using equals:
img 17
img 18
img 19

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

Compare across the classes

Example 01 :

String Vs StringBuffer

img 20

str.equals(buffer) Comparison:

  • The equals method in the String class is overridden to compare the content of two strings. However, when comparing a String with a StringBuffer, they are considered not equal because their types are different.
  • The equals method checks both the content and the type of the objects. Since str is a String and buffer is a StringBuffer, the result of str.equals(buffer) is false.
  • Output is “Both are not equal”
img 21

You can use str.equals(buffer.toString()) to compair the content .

Example 02 :

StringBuilder Vs StringBuilder

img 22

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

  1. str1 == str2 Comparison:
  • The == operator checks for reference equality. In this case, both str1 and str2 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 to true because they reference the same memory location.

2. str1.equals(str2) Comparison:

  • The equals method in the String class is overridden to compare the content of the strings. Since both strings have the same content, str1.equals(str2) will also evaluate to true.

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!

--

--

No responses yet