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

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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 Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}