Create Immutable Class in Java With Example?

Create Immutable Class in Java With Example?

immutable class means if its state cannot change after it is constructed. means once we created object we cant modify exisiting state means instance variable values.

In Java String and all Wrapper classes are Immutable.

Rules to create Immutable class in java

  1. declare the class final,so that we cannot create subclass.
  2. make all fields final and that we cannot change the values.
  3. dont write any setter methods in class


package com.practice;

public final class Account {
private final int accountId;
private final String name;
public Account(int accountId, String name) {
this.accountId = accountId; = name;
public int getAccountId() {
return accountId;
public String getName() {
return name;