Introduction
In arrays, you must have learned that the arrays in Java are objects. We can use all the methods of the class Object with the array. The concept of final arrays is very simple. However, it is not exactly the same as that of a final variable.
A final reference variable can never be reassigned to refer to a different object.
The data contained within the object, on the other hand, can be changed. As a result, the object's state can be changed but not its reference. Because an array is an object, it is referred to by a reference variable, which, if set to final, cannot be reassigned.
We will learn in detail what we discussed above, and it will make much more sense with the help of code examples.
Also see, Duck Number in Java and Hashcode Method in Java.
Final Arrays
Before we discuss final arrays, consider the following example:
public class Main {
public static void main(String[] args) {
// create an array A[] and assign it 5 values.
int A[] = {10, 20, 30, 40, 50};
// create an array B[] and assign it 5 different values
int B[] = {12, 13, 14, 15, 16};
// A refers to B.
// A and B both are object types
A = B;
// the values inside A[] are changed
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
}
}
Output:
12
13
14
15
16
Explanation:
- The original values inside the array A[] was 10,20,30,40,50.
- The original values inside the array B[] were 12, 13, 14, 15, 16.
- When we write A= B, it means that the array variable A, which is of a reference to the array Object, now refers to array B.
- Therefore the contents inside that of A are now the same as that of B.
We saw that everything worked fine, just as we expected. However, consider the below code:
public class Main {
public static void main(String[] args) {
// create a final array A[] and assign it 5 values.
final int A[] = {10, 20, 30, 40, 50};
// create an array B[] and assign it 5 different values
int B[] = {12, 13, 14, 15, 16};
// A refers to B.
// A and B both are object types
// compile time error
// this gives error "cannot assign a value to final variable A"
A = B;
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
}
}
Output:
Main.java:15: error: cannot assign a value to final variable A
Explanation:
- We create a final array using the keyword final, just as we do in case of any final variable.
- When we refer A to B, it gives a compile-time error "Main.java:15: error: cannot assign a value to final variable A."
- It means that a final array cannot refer to any other array or object.
A final array means that the array variable, which is a reference to an object, cannot be changed to refer to anything else. However, the members of the array can be modified.
Here the final Array variable was A. When we tried to refer it to B, we got a compile-time error. However, if we just remove the final keyword from array A[], everything will work fine, as we saw in the previous example.