Search code examples
javawrapperimmutability

Why Float and Double wrapper classes are immutable in java?


Byte, Short and Integer maintains a buffer pool values representing -128 to 127. Character pools values representing '\u0000' to '\u007F'.

So that I can understand that why all above wrapper classes are Immutable.

But, Float and Double do not maintain any buffer pool then what is the purpose of making these classes as Immutable?

I read it from below link:
https://coderanch.com/t/670745/java/Wrapper-Classes-Immutable


Solution

  • First of all, if Byte, Short, Character and Integer are immutable, it would be very inconsistent to make Double and Float mutable.

    Mutability also has it's cost - you cannot share the same resource safely between multiple threads. Copying them on demand is very cheap.

    I also do not see a use case to make them mutable - if you want to use it as some combined in/out parameter, it's a poor design.