Q1) What is an immutable class?
Ans) Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class
Q2) How to create an immutable class?
Ans) To create an immutable class following steps should be followed:
public final class FinalPersonClass {
private final String name;
private final int age;
public FinalPersonClass(final String name, final int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
}
Q3) Immutable objects are automatically thread-safe –true/false?
Ans) True. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.
Q4) Which classes in java are immutable?
Ans) All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger
Q5) What are the advantages of immutability?
Ans)