What are Java Immutable Classes?
In Java, an immutable class is a class whose state cannot be modified once it is created. This is achieved by making all fields in the class final and private, and by not providing any methods that can modify the state of the object.
Here are some examples of immutable classes in Java:
- String: String is a final class in Java, which means that once it is created, its value cannot be changed.
- Integer: The Integer class is also a final class in Java, which means that once it is created, its value cannot be changed.
- BigInteger: The BigInteger class is a final class that represents an immutable arbitrary-precision integer.
- LocalDate: The LocalDate class is an immutable class that represents a date without a time-zone.
- Instant: The Instant class is an immutable class that represents a specific moment in time in the UTC time-zone.
It's important to note that while these classes are immutable, they can still be used in different ways. For example, you can use the +
operator to concatenate two strings, but this creates a new string rather than modifying the original string. Similarly, you can use the add()
method of the LocalDate class to add a certain amount of time to a LocalDate object, but this creates a new LocalDate object rather than modifying the original one.