+ 9
Why I can modify the value of final Array ?
final int[] constantArray = new int[]{1,3,5,7,9}; System.out.println(constantArray[0]); //cannot assign a value to final variable //constantArray = new int[]{2,4,6,8,0}; constantArray[0] = 2; System.out.println(constantArray[0]); Output: 1 2 Why the code can work ?
6 Réponses
+ 5
@ Kuanlin Chen,
"final" keyword means that you can't change the reference of the constantArray, it doesn't mean that the array is immutable!
For example, you can't do something like:
constantArray = new int[10];
// after declaring it "final"
+ 7
Rahul Thanks, your explanation is easy to understand! 🤩
+ 6
salar vahidi Good point, thanks !
+ 1
since array is a reference type not a value type, the final keyword here means the reference or the address that it contains cannot be changed. not the value it points to
if you want to make your array immutable check this out:
https://stackoverflow.com/questions/3700971/immutable-array-in-java
+ 1
you're welcome :)
0
final keyword works as a constant. If you defined the array or single variable with final keyword the values stored in it further can't be changed.