Three images to understand immutability of String in Java

Summary

Java's String objects are immutable, meaning their content cannot be altered after creation. Any operation, such as concatenation, will instead generate a new String object with the modified content. This behavior is demonstrated by how variable assignments initially share references to the same object, but subsequent modifications cause the variable to point to an entirely new String in memory. Developers needing mutable string functionality should utilize StringBuilder or StringBuffer.

String is immutable in Java. This means once a String object is created and instantiated, that object cannot be changed. Any operation on the String object will create a new Object instead of operating on the original content. Below are three images to help you understand String immutability in Java.

Declare a String

String s = "abcd";

s stores the reference to the string content created in the heap.

Assign the String reference to another String variable

String s2 = s;

s2 stores the same reference to the same String object. Since the content is not changed, there will be only one actual object on the heap.

String concatenation

s = s.concat("ef");

Since there is a String operation is performed and the content is changed. s will now store a new reference to the new object created. The original object will not be touched.

If you want to create string which can be updated, you may need to use StringBuilder or StringBuffer.

Source : http://www.hollischuang.com/archives/1230

JAVA STRING

  RELATED

  COMMENT

1
Pin
Jan 12, 2020 at 8:54 pm

thank you :>