Interview Questions

How to create an immutable class in Java?

An immutable class is one who's properties cannot be changed once the class in initialized.

For example, String, Integer,Double etc., are immutable classes in Java.

To create a immutable class in java use the following code.

final class Immutable
{
        private String s = "new";

        public String getS()
        {
                return s;
        }

        public Immutable(String s)
        {
                super();
                this.s = s;
        }      
}

The above class Immutable consist of a property string whose value cannot be modified after any object of the class is created. Not that there is no setter method for the string property and the class is final so that it cannot be extended.