Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 108
Final Local Variables
ОглавлениеThe final
keyword can be applied to local variables and is equivalent to declaring constants in other languages. Consider this example:
5: final int y = 10; 6: int x = 20; 7: y = x + 10; // DOES NOT COMPILE
Both variables are set, but y
uses the final
keyword. For this reason, line 7 triggers a compiler error since the value cannot be modified.
The final
modifier can also be applied to local variable references. The following example uses an int[]
array object, which you learn about in Chapter 4.
5: final int[] favoriteNumbers = new int[10]; 6: favoriteNumbers[0] = 10; 7: favoriteNumbers[1] = 20; 8: favoriteNumbers = null; // DOES NOT COMPILE
Notice that we can modify the content, or data, in the array. The compiler error isn't until line 8, when we try to change the value of the reference favoriteNumbers
.