+ 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 ?

29th May 2018, 3:30 AM
Corey
Corey - avatar
6 ответов
+ 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"
29th May 2018, 4:12 AM
777
777 - avatar
+ 7
Rahul Thanks, your explanation is easy to understand! 🤩
29th May 2018, 4:28 AM
Corey
Corey - avatar
+ 6
salar vahidi Good point, thanks !
9th Mar 2019, 6:26 AM
Corey
Corey - avatar
+ 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
8th Mar 2019, 8:44 PM
salar vahidi
salar vahidi - avatar
+ 1
you're welcome :)
9th Mar 2019, 10:24 AM
salar vahidi
salar vahidi - avatar
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.
29th May 2018, 11:04 AM
Faizal Khan
Faizal Khan - avatar