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

Rishi Raj
Rishi Raj

I am a coder

Updated on: 21-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements