Site icon JavaGoal

final array

We can declare a Final array as the final variable by use of final keyword. As we know we can change the value of final variables in JAVA. In case of array we can change the reference of array. But we can change the value of elements of array. So, the final keyword in java is used with or as the final variable

Example:

Change the value of final variable:

class MainClass
{
    public static void main(String args[])
    {
        final int arr[] = {1, 2, 3}; 
        arr[0] = 10;
        arr[1] = 20;
        arr[2] = 30;
        for(int i = 0; i < 3 ; i++ )
        {
          System.
out.println(arr[i]);
        }
        // You can’t re-assign it. it will throw compilation error
       // arr = new int[5];
    }
}

Output:

10

20

30

Hence, As we discuss we can’t change the reference of final array.

Example:

class MainClass 
{ 
    public static void main(String args[]) 
    { 
        final int arr[] = {1, 2, 3};  
        arr[0] = 10;
        arr[1] = 20;
        arr[2] = 30;
        for(int i = 0; i < 3 ; i++ )
        {
           System.out.println(arr[i]);
        }
    	
        //You can't re-assign it. it will throw compilation error
       arr = new int[5];
    } 
}

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
          The final local variable arr cannot be assigned. It must be blank and not using a compound assignment
 
          at PackageOne.ClassOne.main(ClassOne.java:15
)
 

Exit mobile version