I understand the reason behind String class being immutable. Would like to know for what reasons the other wrapper classes like Integer,FLOAT,LONG are made immutable?
Printable View
I understand the reason behind String class being immutable. Would like to know for what reasons the other wrapper classes like Integer,FLOAT,LONG are made immutable?
Can you think of any reasons? I wouldn't spend too much time worrying about why certain decisions were made about the language. Why is it called a JFrame instead of a JForm? Why is it int and not integer? It's usually best just to accept the fact of the situation and move on.
I can think of at least one reason for making them immutable though. Say you have a class that contains an Integer that you want other classes to be able to access, but not change. You might do something like this:
That's all well and good, right? The Integer is private so other classes can't access it directly, and there's only a getter method, so other classes can't change it. But if Integer was not immutable, another class could do this:
Code java:IntegerHolder holder = new IntegerHolder(); holder.getI().setInt(10000);
Making a class immutable has advantages for both Garbage Collection and security. Security wise, one cannot alter the value of the object and leave it in an unexpected state. Examples and how this relates to threading is discussed in the following:
See Immutable Objects (The Java™ Tutorials > Essential Classes > Concurrency)
For a discussion on the advantages for garbage collection, see
Java theory and practice: Garbage collection and performance
If a class has no reason to have its behavior overridden or inherited (as would be the case for Integer, Long, etc...), there's a good chance I will make the class immutable for the above reasons.
well Immutability offer several advantages :
1) Immutable object like String and wrapper can be used as key in HashMap (those are most used keys anyway)
2) Immutability enable them to be reused in application. valueOf() often return same object if its immutable
3) Immutable are inherently thread-safe
Be careful in getting Immutability confused with Wrapper classes and caching (points 1 and 2). Immutability does not have much to do with being able to wrap a primitive and place it into a Map (it does from the context of thread safety and the hashCode() method contract - and FWIW it is quite relative to say they are the most used keys), and Immutability has nothing to do with the caching involved with the valueOf method of those classes (and just to note, is incorrect to say it always returns the same object - only a few select values are actually cached, in which case for only a few select values will you get the same object)