Java - Class Object Immutable

What is am Immutable Object?

An object whose state cannot be changed after it is created is called an immutable object.

What is an immutable class?

A class whose objects are immutable is called an immutable class.

What is mutable?

If an object's state can be changed after it has been created, it is called a mutable object, and its class is called a mutable class.

Mutable Example

An Example of a Mutable Class Whose Object's State Can Be Changed After Creation

class IntHolder {
        private int value;

        public IntHolder(int value) {
                this.value = value;
        }
        public void setValue(int value) {
                this.value = value;
        }

        public int getValue() {
                return value;
        }
}

The value instance variable defines the state of an IntHolder object. You create an object of the IntHolder class as shown:

IntHolder holder = new IntHolder(101);
int v = holder.getValue(); // will return 101
// Change the value
holder.setValue(505);
int w = holder.getValue(); // will return 505

Immutable Example

All you need to do is to remove the setValue() method from it to make it an immutable class.

class IntWrapper {
        private final int value;

        public IntWrapper(int value) {
                this.value = value;
        }

        public int getValue() {
                return value;
        }
}

This is how you create an object of the IntWrapper class:

IntWrapper wrapper = new IntWrapper(101);

An Example of an Externally Immutable and Internally Mutable Class

class IntWrapper {
        private final int value;
        private int halfValue = Integer.MAX_VALUE;

        public IntWrapper(int value) {
                this.value = value;
        }

        public int getValue() {
                return value;
        }

        public int getHalfValue() {
                if (this.halfValue == Integer.MAX_VALUE) {
                        this.halfValue = this.value / 2;
                }
                return this.halfValue;
        }
}