Java Interview Questions

February 13, 2010

why string is immutable ?

Filed under: Java Interview Questions — Tags: , , , — Sachin Kakkar @ 3:00 am

In java, Strings are handling in Pool format.

For example:

String str1 = “xyz”;

This string(str1) will be stored into memory in particular address. When we defining new String with same array of characters like

String str2 = “xyz”;

Now JVM will check in String Pool where there is same characters are available or not. If two Strings are match the JVM will refer str1 address to str2. Now the str1 and str2 referring the same characters in same memory location. This is a good idea for increasing memory efficiency.

When we change the str1 characters, the changes will be reflected to str2. Because both str1 and str2 variables are referring the same memory location. For avoiding this we are keeping String as immutable. However we can use StringBuffer if you want to do modifications in the string.

Making String immutable, makes it thread safe and thus imporves performance.

Once a string object is created no changes can be made to it. If a string is modified in code a new object will be

created. That is why string is immutable.

Advertisement

1 Comment »

  1. See here for some more reason of String immutability

    http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html

    Comment by Javin Paul — October 23, 2010 @ 10:47 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Theme: Shocking Blue Green. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.