Last Updated: 20 April, 2023
In the tutorial, we are going to discuss what immutable objects are and how to create a custom immutable class in Java.
In Java, an immutable object is one whose state cannot be changed once it has been created. The state of such an object can be changed by creating a new copy with the intended changes. Immutable classes are useful for representing values that should not be changed after they are initialized.
📝 Java has provided many built-in immutable classes, such as String, wrapper classes (Integer, Long, Float, etc.), BigInteger, BigDecimal, Locale, etc.
To create an immutable class in Java, we should follow these steps:
Let's understand the custom immutable class with the help of the given example below.
Java Custom Immutable Class Example
Output
Student Name: Shreyansh Shanu
Student Class: Nursery
Student Roll No.: 11
Use of Immutable class in Java
Due to the fact that they cannot change state, immutable objects are particularly useful for concurrent applications. This is because they cannot be corrupted or observed in an inconsistent state due to thread interference.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com