Can you modify a final object reference in Java?

A final object reference cannot be reassigned to point to another object once it has been initialized. However, if the object itself is mutable, its internal state can still be changed through that reference.

Key Points: • The final keyword makes the reference constant, not the object. • You cannot assign a new object to a final reference after initialization. • Mutable objects referenced by a final variable can still have their fields or contents modified. • To achieve complete immutability, both the reference and the object's state must be immutable.

Example: If a List is declared as final, you can add or remove elements from the list, but you cannot make the reference point to a different List object.

Code Example:

import java.util.ArrayList;
import java.util.List;

public class FinalReferenceDemo {

    public static void main(String[] args) {

        final List<String> names = new ArrayList<>();

        names.add("John");

names.add("David"); // Allowed

        // names = new ArrayList<>(); // Compilation Error

        System.out.println(names);
    }
}

Interview Tip: A concise interview answer is: A final object reference cannot be reassigned to another object, but the object's internal state can still be modified if the object is mutable. The final keyword protects the reference, not the contents of the object.