Three images to understand immutability of String in Java

  sonic0002        2016-03-11 20:58:28       4,985        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 

           

  RELATED


  1 COMMENT


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

thank you :>



  RANDOM FUN

A programmer's dream

Last night I had a dream. In that dream, my boyfriend was shopping with another woman. The first reaction of mine in that dream was to check the source code... The end result is it's still that woman but not me after a long time debugging, so I have to comment out that woman and run the program agai

  SUPPORT US