
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Final Arrays in Java
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object.
However, the data within the object can be changed. So, the state of the object can be changed but not the reference. As an array is also an object and it is referred by a reference variable which if set as final then cannot be reassigned. Let's see the examples for further explanation.
Example
public class Tester { public static void main(String []args) { final int[] arr = {1,2,3}; //We can modify the final object's properties arr[1] = 4; for(int i = 0;i < arr.length ; i++) { System.out.println(arr[i]); } } }
Output
1 4 3
Now try to change the reference variable. Compiler will throw an error during compilation.
Example
public class Tester { public static void main(String []args) { final int[] arr = {1,2,3}; int[] arr2 = {4,5,6}; //We cannot modify the final refernce arr = arr2; for(int i = 0;i < arr.length ; i++) { System.out.println(arr[i]); } } }
Output
Tester.java:6: error: cannot assign a value to final variable arr arr = arr2; ^ 1 error
Advertisements