Why string class is immutable




















Well, that's all for now. In this post, we discussed some reasons why String is immutable. Hope you have enjoyed this post! See the original article here. Thanks for visiting DZone today,. Edit Profile. Sign Out View Profile. Over 2 million developers have joined DZone.

String: Why it Is Immutable? Want to learn more about why String is immutable? Check out this post where we take a look at Strings and what it means to be immutable. Like 9. Join the DZone community and get the full member experience. Join For Free. Why String Is Immutable? Pankaj I love Open Source technologies and writing about my experience about them is my passion.

Follow Author. Comments Nilakshi Patil says:. September 13, at am. Pankaj says:. Rohit says:. April 3, at am. Ashok says:. May 6, at am. Nilakshi Patil says:. September 12, at pm. Santosh Gupta says:. January 27, at am. Tanmoy Ghosh says:. January 30, at am. December 18, at pm. Akshayraj A Kore says:. July 10, at pm. Sudha says:. February 7, at am.

February 7, at pm. Sonam Devikar says:. August 18, at am. Abhi says:. March 5, at am. Kiran Pophaler says:. August 8, at am. Ankush Raina says:. January 16, at pm. Sachin says:. Before you guys tear my opinion to shreds please read ahead Strings are backbone of Java or for that matter any other programming language.

As we have seen thousand examples in this great blog itself, for example classloaders uses classname to load a class which is a string, usernames, passwords, database connection names etc. Now lets assume for a second that String were not immutable what would happen? String references pointing to litrals in constant pool would keep on changing the contents there hence a havoc would occur.

To fix this java designers would have to remove the constant pool all together. Thus we would have to create a new instance of string all the time which would go into the heaps. Tons of string would result in out of memory errors hence impact the performance of all the java applications. Hi Niraj, Good comment. Performance would definitely will be in mind of Java designers, because whole idea of String pool is caching. Immutability, String pool, Security, Performance these all things put together nicely for String being immutable.

If this was the answer given in an interview that I was giving, you would not get the job. It misses the fundamental reason for using an immutable classes, and that is to allow this object to be shared efficiently without fear of having the underlying value change. All of the listed reasons are secondary to this fundamental point, so not to mention it means that you are not seeing cause and effect in the right direction.

If you take the discussion in point 5 for example, it does not make any sense. These classes were built on the assumption that String was safe to share.

If they weren't safe, they would never be used in a context that required safety. It's like saying that glue is sticky because if it weren't, my furniture would fall apart. Honestly, I take the security argument with caution. Nothing prevents a mutable object holding the immuatable String to change the reference and so refer to another String. More, without proper security policy, nothing prevents introspection to change an existing String value and mess up the String pool.

More interesting, explicitly creating a new instance allow you to avoid some of the problems. I am really unable to understand immutable object is not modifiable meaning.. Give me an example of mutable class and its immutability.. Thank you for noticing me. I do not very much agree with point 4 related to hashcode.

Can we use an object as key in hashmap whose hashcode can change once stored in hashmap? Good post. Only one note: the hashcode caching is not the reason for making String immutable, but visa versa hashcode caching mechanism is used because String is immutable. Java uses the concept of string literal.

Suppose if there are 5 reference variables ,all references to one object. That is why string is immutable in java. The two main reasons why strings are immutable in many modern languages, including Java, are security and performance or, more precisely, chance for optimizations. The fact that strings are final is to ensure their immutability by forbidding anyone from extending them and making them mutable again. Annonymous: We use String Pool because it stores only one reference to String literal eg.

Now if you create two "Test" String using new operator eg. So i hope you understand string pool is saving time on string related memory operations. Good post! Thanks in advance. A String value in Java is immutable but a String variable is not final. The term "final" specifically marks a memory reference variable as a constant that cannot change. The value to which a String variable refers in memory can be changed. In other words, the variable can refer to a different value, even though the original value is immutable.

Hi, I executed below lines of code and unable to understand the output can u plz explain. The output is right and the reason behind this is while writing "test". So the reference become lost. And while printing it prints the previous value of string.

You need to be careful to store the modified reference otherwise it can really create hard to find bugs in your code. Hi Javin, one more reason for String being immutable could be that String is more like the primitive type but represented as object. Since java uses pass by value it makes sense for passing an immutable object to the methods as parameter so that pass by value behavior is maintained.

Because of immutability, you don't need to worry about those kind of threats. This reason also gel with, Why String is final in Java, by making java. String final, Java designer ensured that no one overrides any behavior of String class. Keyur, in classloading name of class is passed as String, if String wasn't immutable its possible to change the name of that String from somewhere else, which can compromise security by loading different class.

Good explanation, need to ask one thing, Is string pool stores the hashcode of the string or only value. In this example Strign A and String B will have different memory location. Anonymous, that's the hypothetical scenario I was explaining that why its MUST for String to be final if you want to have something like String pool.

I hope it make sense to you now. I do no think any of the points are of relevance as you can always use reflection to play around with values. Sapna, Java designer knows that String will be used heavily in Java application and there would be so many String object all around which will take lot of memory.

To avoid that they thought about sharing String object between clients and that's why they made it Immutable and created String pool. HI Javin, Recently interviewer asked me What is the significance of creating String using new operator if we have string literal functionality for the same? Do you have any thoughts on it? All of those posters who say String isn't immutable because they can use introspection to change its private internal state need to read up on what a SecurityManager does during the reflection call to change its value.

Then load one and try to change a String's underlying value. Just because we developers frequently ignore security doesn't mean that your code can count on reflection to allow it to do naughty things. As I understand String, I don't see any use of new operator while creating String object. Can any one explain where do we need new operator to create String? When jvm is loaded into memory as instance of java. Class,how much memory taken by jvm into the ram so that it can load the classes and perform their operations.

One advantage of making String immutable is for saving memory. When your program grows the number of String instances it creates also grows and if you don't cache String constants you end up with lots and lots of String in your heap space.

Actually new creates a new object each time. Literal, if the value exists in the string pool already then you will get that itself, instead of creating new object. So using Sting literal is always better and new should not be used until required.

Immutability certainly leads to more memory and CPU usage if more and more new strings are created due to overcome immutability. In memory constrained and battery powered devices immutability would slow the system.. But looks like the way JVM makes use of immutability of Strings, makes programs secure, safer and faster.

In java many value define like pie is 3. Post a Comment. The string is Immutable in Java because String objects are cached in the String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client. For example, if one client changes the value of the String "Test" to "TEST", all other clients will also see that value as explained in the first example.

Since caching of String objects was important from performance reason this risk was avoided by making String class Immutable.

At the same time, String was made final so that no one can compromise invariant of String class like Immutability, Caching, hashcode calculation, etc by extending and overriding behaviors. Another reason why String class is immutable could die due to HashMap.

Since Strings are very popular as the HashMap key, it's important for them to be immutable so that they can retrieve the value object which was stored in HashMap. Since HashMap works in the principle of hashing , which requires the same has value to function properly. Mutable String would produce two different hashcodes at the time of insertion and retrieval if contents of String were modified after insertion, potentially losing the value object in the map.



0コメント

  • 1000 / 1000