I am trying to understand what happens if I reassign a value to array element which is final, this is the code :
public class XYZ {
private static final
The final
keyword does not mean you cannot change the state of the object, but only that the reference marked as final
will remain constant. For example, you won't be able to do things like
final String[] ABC = {"Hello"};
ABC = new String[3]; // illegal
ABC = someOtherArray; // illegal;
ABC[0] = "World"; // legal
When final
is applied to a variable, that only means that it cannot be reassigned once initialized. That does not prevent the object itself from being modified. In this case, you are modifying the array object. So this is fine:
ABC[0] = " World!!!";
But this would not have been allowed.
ABC = new String[]{" World!!!"};
My response is same as the others that "final" only prevents the variable from pointing to a new object, it does not prevent the object itself updates its members.
Additional response about you mention that the output seems to append the string, but it is not, because you have a print statement before the assignment, and one after the assignment.
Arrays
are mutable Objects unless created with a size of 0.Therefore,you can change the contents of an array.final
only allows you to prevent the reference from being changed to another array Object.
final String[] ABC ={"Hello"};
ABC[0]="Hi" //legal as the ABC variable still points to the same array in the heap
ABC = new String[]{"King","Queen","Prince"}; // illegal,as it would refer to another heap Object
I suggest you use Collections.unmodifiableList(list)
to create a immutable List.See the javadoc here (unmodifibale list).
You can do the following
String[] ABC = {"Hello"};
List<String> listUnModifiable = Collections.unmodifiableList(java.util.Arrays.asList(ABC));
At any point of time,you can get the array by calling listUnModifiable.toArray();