Immutable Objects in java

Wed, Nov 20, 2019

Read in 1 minutes

What is immutable?

If you cannot change the content of the object, then that is called immutable objects. String and all other wrapper classes Integer, Double are immutable.

How to create custom immutable objects?

public final class CreditCard {
	private final Long cardNumber;
	private  final String cardHolderName;
public CreditCard(Long cardNumber, String cardHolderName) {
		this.cardNumber = cardNumber;
		this.cardHolderName = cardHolderName;
	public Long getCardNumber() {
		return cardNumber;
	public String getCardHolderName() {
		return cardHolderName;
	public static void main(String[] args) {
		CreditCard card= new CreditCard(1243536L, "rty");

If you try a change the content of the object, you will get below error.


So, If you want to change the content fo the object, you have to create a new object.