Java Cracker

-by Kausik Jana

Why String is immutable in java?

Why String is immutable in java?

There are several reasons why the String object is immutable in java.

1. Security Issue:

Imagine String object isn’t immutable and you need to open a secure file to authenticate the users. Let’s assume that two users User1 and User2 are going to log in and they have their own password file “Password1” and “Password2” respectively. Now user1 logged in into the system and somehow he able to change the file name (File class uses the file name as String object)as “Password2” before JVM makes native OS call to open the file. In a result User1 can access the User2’s file. So it looks like a bigger security issue.

With immutable String object Java can ensure that the file name string object is encapsulated with the respective file object and no one can change the actual value of the string object.

2. String Pool Issue:

If  String is mutable:

Let’s assume that we have a String object “Hello” and two references refer to “Hello” e.g

String s1 = “Hello”;

String s2 =”Hello”;

fig-1

Now I concatenate one more String object called s3 (“Kausik”) to s2 String so the new value of s2 will be “HelloKausik”.

So what is the value of s1 now? The value is “HelloKausik” but it is not as expected.

fig-2

If  String is immutable:

Let’s assume that we have a String object “Hello” and two references refer to “Hello” e.g

String s1 = “Hello”;

String s2 =”Hello”;

fig-1

Now I concatenate one more String object called s3 (“Kausik”) to s2 String so the new value of s2 will be “HelloKausik”.

So what is the value of s1 now? The value of s1 is “Hello” because String object is immutable e.g Object’s value can’t be changed once initialized. A new object will be created and s2 will refer to this as shown in the below picture.

 

immutableString

 

So, a String object can be used more than once without having to create or reclaim. It will increase the performance.

3. Thread Safe:

As String is an immutable object, it can be accessed by multiple threads and no thread can change the value of the particular object. So String objects are thread-safe and can be shared with multithreading environment.

1 Comment

Leave a Reply

Your email address will not be published.

*

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>

© 2014 Java Cracker

Proudly Powered by Wordpress