Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Explaining String Immutability

DZone's Guide to

Explaining String Immutability

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}