Final Arrays in Java

Java Programming Java8Object Oriented Programming

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
raja
Published on 14-Aug-2018 09:58:19
Advertisements