简体   繁体   中英

Concept of Immutability of String in Java

i know the reason, why String is immutable but my question is why the concept of immutability sticks to only String class in java , why it won't apply to others.

one of the reason i found why it is immutable is HERE

but why not all other classes like Integer and so on.. how java people decided changing their values might not effect ..

please explain .

The point is that you could confuse a String (which is an Object) with a primitive type. In fact, The way strings typically appear in Java programs can lead to confusion. There are shortcuts available for strings that are not available for other objects in Java. These shortcuts are highly used and they give strings the appearance of a primitive data type. But, strings are objects and they possess all the attributes and behaviours of objects in Java

When designing a class, to make it immutable or not is a design choice and usually a tradeoff. The classes String and Integer were made immutable for many reasons including security.

A class like java.util.Random is all about managing some state, so it has to be mutable.

A class like java.awt.Rectangle is mutable, which has the advantage of saving memory management costs when you modify one rather than create a new one, but unfortunately it means that when a Rectangle instance that's shared (eg by two different window objects), changing it for one of them will change it out from under the others, causing unhappy surprises. Modern garbage collectors are very efficient [I hear they're more efficient than C's malloc() and free() ] so mutability may not actually save memory management overhead, certainly not if you often have to copy objects to protect against accidental shared changes.

You can freely share an immutable object without worrying about it changing out from under you.

Integer is immutable, so each operation on it creates a new instance.

Immutable does not mean that a refernece can never assign another value. For example, String is immutable too, but we can do this:

String ex = "good";    // ex == "good"
ex = ex + "morning";    // now ex == "goodmorning"

So what happened there? Since String is immutable, clearly "ex" was not changed. But it now being assigned something different. This is because "ex" is now a completely newly instantiated object.

So this is same the case of Integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM