Over a million developers have joined DZone.

Explaining String Immutability

· Java Zone

Learn more about how the Java language, tools and frameworks have been the foundation of countless enterprise systems, brought to you in partnership with Salesforce.

Here we are creating a String object. String is a 16-bits unicode object.

String str1 = new String("Hello");

Also a more simplified form - String str2 = "World";  Now we created two different object with two references.Lets say we create a new String reference and assign the String str1 to it.

String str3 = str1;

Now str1 and str3 point to same String object 'Hello'. Now we have three references and two String objects. Now let’s try concat method which will try to append the literal to the end of a string.

str1 = str1.concat(" Example ");

 Now what will be the value of str1 - 'Hello Example' .The value of str1 changed, then why do we say string is immutable. Let’s try to understand what is happening behind. Actually java creates a copy of str1 and appends the new string literal to the copy, not the original object. The original String object will remain in the memory and will be considered as lost.

Let’s try another way

str1.concat( " adding " );  

Here we create a new string object 'Hello Example Adding' and this String object will be lost since it is not referenced.

String constant pool

To make Java more memory efficient, the JVM sets aside a special area of memory called the "String constant pool." When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created Sun Certified Programmer & Developer for Java 2 Study Guide

Discover how the Force.com Web Services Connector (WSC) is a code-generation tool and runtime library for use with Force.com Web services, brought to you in partnership with Salesforce.


The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}