What is immutable object in Java?

An immutable object in Java is the object that can not be changed after it is initialized. For example String object is immutable because you can not change String object's content. when you write str = "Hello"; and then str ="World"; you didn't erase the "Hello" String object, you create another object "World" and assign the reference to str variable.

Being immutable is a design choice, it's a good practice, the rule of thumb is use immutable whenever possible, when you have to mutate, limit the mutation, it's tolerable to mutate for the sake of performance. In language like C/C++, there is no built-in immutable data types, the only way to be immutable is using const, there are experienced C++ programmers who use const so heavily that they call themselves const nazi. In Java you may never need to be an immutable nazi, but it's still very beneficial to remember be immutable is good.

As the application development world involves more and more concurrency, the immutability gets more important for the benefits it brings to concurrency programming. There are new programming language especially the functional one has built-in support for immutability, such as Clojure, a LISP implemented on JVM in which most basic data structure like array, list, map, set are immutable.

Java has some built-in immutable objects like String, there are also third libraries that provides immutable version of list, hash map, array and other data structures in Java collection, called immutable collection.

Why use immutable object?

  • They are thread safe, because their state never change, have no synchronization issues
  • Avoid aliasing problems.
  • Instances can be reused. You can cache the created instance and don't have to create it and destroy it every time.
  • Easier to reason the code for avoiding side effect caused by mutating variable.

A good Java practice is make a class immutable whenever possible.

How to declare immutable object?

Make a class immutable by the following rules:

  • Make the class final ensure the class can not be overridden.
  • Make fields private and final.
  • Ensure the object must be constructed in single step.
  • Don't provide setXXX method.

The String class is an example of immutable class:

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence
    private final char value[];
    private final int offset;
    private final int count;
    private int hash; // Default to 0
    private static final long serialVersionUID = -6849794470754667710L;