Java array final element change value
I am trying to figure out what happens if I reassign a value for an array element that is final, this is the code:
public class XYZ {
private static final String[] ABC = {"Hello"};
public static void main(String[] args){
System.out.println(ABC[0]);
ABC[0] = " World!!!";
System.out.println(ABC[0]);
}
}
ABC is the final array and it initially has it "Hello"
initially, but when I reassign it to " World!!!"
, it must either exceed the previous value or give a compile error to reassign the final variable. This program works fine and this is the output:
run:
Hello
World!!!
BUILD SUCCESSFUL (total time: 0 seconds)
source to share
Arrays
are volatile objects unless created with size 0. Therefore, you can change the contents of the array. final
allows you to prevent the reference to another array object from being replaced.
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 to create an immutable list. Look here for the javadoc (unmodifibale list). Collections.unmodifiableList(list)
You can do the following
String[] ABC = {"Hello"};
List<String> listUnModifiable = Collections.unmodifiableList(java.util.Arrays.asList(ABC));
At any given time, you can get the array by calling listUnModifiable.toArray();
source to share
The keyword final
does not mean that you cannot change the state of the object, but only that the link 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
source to share
When final
applied to a variable, it only means that it cannot be reassigned after initialization. This does not prevent the object from changing. In this case, you are modifying the array object. So this is ok:
ABC[0] = " World!!!";
But that wouldn't be allowed.
ABC = new String[]{" World!!!"};
source to share
My answer is the same as others, that "final" only prevents the variable from being pointed to a new object, it does not prevent the object itself from updating its elements.
A supplementary answer about you mentions that the output appears to add a line, but it doesn't, because you have a print statement before the assignment and one after the assignment.
source to share