Immutable objects are instances whose state doesn’t change after it has been initialized. For example, String is an immutable class and once instantiated its value never changes.
Some immutable classes in Java:
- The wrapper classes for the primitive types: java.lang.Integer, java.lang.Byte, java.lang.Character, java.lang.Short, java.lang.Boolean, java.lang.Long, java.lang.Double, java.lang.Float
- Most enum classes are immutable, but this in fact depends on the concrete case.
- java.math.BigInteger and java.math.BigDecimal (at least objects of those classes themselves)
- java.io.File. Note that this represents an object external to the VM (a file on the local system), which may or may not exist, and has some methods modifying and querying the state of this external object. But the File object itself stays immutable.
Example with mutable refs
This modified text is an extract of the original Stack Overflow Documentation created by following contributors
and released under CC BY-SA 3.0