Junior — Middle
What does immutability of objects in Java entail and which classes are immutable by default?
sobes.tech AI
Answer from AI
Immutability of objects in Java means that once an object is created, its state (field values) cannot be changed. This enhances security and simplifies multithreaded work, as immutable objects do not require synchronization.
A class is considered immutable if:
- All fields are declared as final.
- The class is declared as final or has no methods that can change the state.
- There are no setters or other methods that modify fields.
- If fields are references to objects, then these objects are also immutable or are copied upon transfer.
Examples of immutable classes in the Java standard library:
String- Wrappers of primitive types:
Integer,Long,Double,Boolean, etc. BigInteger,BigDecimal
Example of creating your own immutable class:
public final class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}