Why String is immutable in java ?


This is the good interview question in java I face this question in one of my interview so I will share some important point about why String is not immutable in java.

You all know the String Constant pool. String Constant pool is pool where String object held by java.

If you are make any String object first java compiler check this is available in string constant poll or not if it available then it point that reference to the other object if it is not available in String constant pool then it’s create a new memory area for that particular String .

For example.

public class StringTest {

 public static void main(String[] args) {

              String s1="hello";

              String s2="world";

              String s3="hello";

       }

}

In this example we are create a three String s1,s2,s3 . S1 and s2 have a different value then java compiler create a separate  memory In String Constant pool.  But in case of s3 its check the Constant pool first s3 is same value as s1 then its point only the reference of s1 to s3 .That means s1 and s3 content same value . That is concept of  String Constant pool.

Why String is not immutable in java ?

In privies paragraph I will share a concept of Constant pool. In this paragraph I will show why string is not immutable in java then lets goo.

Example.

public class NewThread {

       public static void main(String[] args) {

              String s1="hello";

              String s2="world";

              String s3="hello";

              s1=s1+s2;

              System.out.println(s1+"   "+s3);

       }

} 

Out put is

S1= Hello World

S3= Hello

 

In this case S1 and s3 both are point the same memory in Constant pool . but after the adding the both s1 and s2  , s1 has new value then java compiler check this value are available in constant pool or not  if it is not available in constant pool then is create a new memory in constant pool. Then s1 point new location in pool but s3 point same location that is point previous.

I n case of  S1= S1+S2 S1 Point new location but s3 point same location where is hello is held by java.

If String is mutable in java java compiler cant create a new memory  area for String s1 then unfortunately all other object are also change those attach with same memory . That’s why string is not immutable in java.

* indicates required Email Address * First Name * Email Format html text mobile

Comments

  1. Siddu says

    How annotations works internally? Ex: @Override how will it check method being overridden by subclass or not? When i saw the source code no code in it without having any logic. .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Loading Facebook Comments ...