Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Three images to understand immutability of String in Java

  sonic0002        2016-03-11 20:58:28       4,450        1    

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 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  1 COMMENT


Pin [Reply]@ 2020-01-12 20:54:28

thank you :>