Конечные массивы в Java

Опубликовано: 15 Февраля, 2022

Predict the output of following Java program.

class Test 
{
    public static void main(String args[])
    {
       final int arr[] = {1, 2, 3, 4, 5};  // Note: arr is final
       for (int i = 0; i < arr.length; i++)
       {
           arr[i] = arr[i]*10;  
           System.out.println(arr[i]);          
       }      
    }    
}

Выход:

 10 
20 
30 
40 
50

The array arr is declared as final, but the elements of 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. For example, the following program 1 compiles without any error and program 2 fails in compilation.

// Program 1
class Test 
{
    int p = 20;
    public static void main(String args[])
    {
       final Test t = new Test();       
       t.p = 30;
       System.out.println(t.p);   
    }    
}

Output: 30

// Program 2
class Test 
{
    int p = 20;
    public static void main(String args[])
    {
       final Test t1 = new Test();       
       Test t2 = new Test();
       t1 = t2; 
       System.out.println(t1.p);      
    }    
}

Вывод: ошибка компилятора: невозможно присвоить значение конечной переменной t1

Таким образом, окончательный массив означает, что переменная массива, которая на самом деле является ссылкой на объект, не может быть изменена для ссылки на что-либо еще, но члены массива могут быть изменены.

As an exercise, predict the output of following program

class Test 
{
    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]);          
    }    
}

Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .