Sunday, July 9, 2017

Final Arrays in Java


When we make primitive variables as final, it means that they’re constant and there values can’t be change.
But by making array final, array can't refer to anything else but its elements value can change.
Array are nothing but objects and by making it final,we’re stating that its reference can’t point to anything else now. On the other hand, array values can be manipulated as they’re not binded with final modifier.

See below example which covers all scenarios for better understanding :

public class TestFinal {
    
     int p = 20;
     public static void main(String[] args) {
         
          /* Program 1 – Works fine,array is fixed*/
          final Integer[] array ={1,2};
          System.out.println(array[0]);
          System.out.println(array[1]);
          array[0]=10;
          System.out.println(array[0]);
         
          /* Program 2 -Works fine */
          final TestFinal t = new TestFinal();      
          t.p = 30;
          System.out.println(t.p);
        
          /* Program 3 - Compile time error */
          final TestFinal t1 = new TestFinal();      
          TestFinal t2 = new TestFinal();
          t1 = t2;
          System.out.println(t1.p);

     /* Program 4- Compile time error*/
          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]); 
         
     }
}


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 array can be modified.

No comments:

Post a Comment