Why won't declaring an array final make it immutable in Java? Doesn't declaring something final mean it can't be changed?
From question related to immutable array it's clear that declaring an array final doesn't make it unchangeable.
The following is possible.
final int[] array = new int[] {0, 1, 2, 3};
array[0] = 42;
My question is: What is the function of declaring final here then?
When a variable is declared with the final keyword, its value can't be modified, essentially, a constant. Immutability: In simple terms, immutability means unchanging overtime or being unable to be changed. In Java, we know that String objects are immutable means we can't change anything to the existing String objects.
Output Explanation: The array arr is declared as final, but the elements of an array are changed without any problem. Arrays are objects and object variables are always references in Java. So, when we declare an object variable as final, it means that the variable cannot be changed to refer to anything else.
No, it is not mandatory to have all properties final to create an immutable object. In immutable objects you should not allow users to modify the variables of the class. You can do this just by making variables private and not providing setter methods to modify them.
final
is only about the reference that is marked by it; there is no such thing as an immutable array in Java. When you say
private final int[] xs = new int[20];
you won't be allowed to say
xs = new int[10];
later on. That's all what final
is about. More generally, ensuring that an object is immutable is often hard work and full of a range of subtleties. The language itself doesn't give much to this end out of the box.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With