Final Arrays in Java
Last Updated :
04 Apr, 2023
As we all know final variable declared can only be initialized once whereas the reference variable once declared final can never be reassigned as it will start referring to another object which makes usage of the final impracticable. But note here that with final we are bound not to refer to another object but within the object data can be changed which means we can change the state of the object but not reference. So, as we all know that arrays are also an object so final arrays come into play. The same concept does apply to final arrays that are we can not make the final array refer to some other array but the data within an array that is made final can be changed/manipulated.
Illustration:
Java
import java.util.*;
class GFG {
public static void main(String[] args)
{
final int [] arr = { 1 , 2 , 3 , 4 , 5 };
arr[ 4 ] = 1 ;
for ( int i = 0 ; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
|
Implementation:
Java
import java.util.*;
class GFG {
public static void main(String args[])
{
final int arr[] = { 1 , 2 , 3 , 4 , 5 };
for ( int i = 0 ; i < arr.length; i++) {
arr[i] = arr[i] * 10 ;
System.out.println(arr[i]);
}
}
}
|
Output Explanation: The array arr is declared as final, but the elements of an array are changed without any problem. Arrays are objects and object variables are always references in Java. So, when we declare an object variable as final, it means that the variable cannot be changed to refer to anything else.
Example A:
Java
class Test {
int p = 20 ;
public static void main(String args[])
{
final Test t = new Test();
t.p = 30 ;
System.out.println(t.p);
}
}
|
Example B:
Java
class GFG {
int p = 20 ;
public static void main(String args[])
{
final GFG t1 = new GFG();
GFG t2 = new GFG();
t1 = t2;
System.out.println(t1.p);
}
}
|
Output: Compiler Error: cannot assign a value to final variable t1
Conclusion: Above program compiles without any error and program 2 fails in compilation. Let us discuss why the error occurred.
So a final array means that the array variable which is actually a reference to an object, cannot be changed to refer to anything else, but the members of the array can be modified. Let us propose an example below justifying the same.
Example:
Java
class GFG {
public static void main(String args[])
{
final int arr1[] = { 1 , 2 , 3 , 4 , 5 };
int arr2[] = { 10 , 20 , 30 , 40 , 50 };
arr2 = arr1;
arr1 = arr2;
for ( int i = 0 ; i < arr2.length; i++)
System.out.println(arr2[i]);
}
}
|
Output:
Example :
Java
import java.io.*;
public class FinalArrayExample {
public static void main(String[] args)
{
final int [] numbers = { 1 , 2 , 3 , 4 , 5 };
numbers[ 0 ] = 10 ;
System.out.println(
"Array after modifying first element: "
+ arrays.toString(numbers));
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...