Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't declaring an array final make it immutable in Java?

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?

like image 690
nayef Avatar asked Dec 20 '12 20:12

nayef


People also ask

Does declaring an object final makes it immutable?

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.

Can we declare array as final in Java?

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.

Does an immutable class need to be final?

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.


1 Answers

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.

like image 187
Marko Topolnik Avatar answered Oct 22 '22 21:10

Marko Topolnik