Final arrays in Java

link 0

Predict the output of following Java program.

classTest
{
    publicstaticvoidmain(String args[])
    {
       finalintarr[] = {1, 2, 3, 4, 5};  // Note: arr is final
       for(inti = 0; i < arr.length; i++)
       {
           arr[i] = arr[i]*10
           System.out.println(arr[i]);         
       }     
    }   
}

Output:

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 fails in compilation.

// Program 1
classTest
{
    intp = 20;
    publicstaticvoidmain(String args[])
    {
       finalTest t = newTest();      
       t.p = 30;
       System.out.println(t.p);  
    }   
}

Output: 30

// Program 2
classTest
{
    intp = 20;
    publicstaticvoidmain(String args[])
    {
       finalTest t1 = newTest();      
       Test t2 = newTest();
       t1 = t2;
       System.out.println(t1.p);     
    }   
}

Output: Compiler Error: cannot assign a value to final variable t1

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.

As an exercise, predict the output of following program

// Program 2
classTest
{
    intp = 20;
    publicstaticvoidmain(String args[])
    {
       finalTest t1 = newTest();      
       Test t2 = newTest();
       t1 = t2;
       System.out.println(t1.p);     
    }   
}

Disclaimer: This does not belong to TechCodeBit, its an article taken from the below
source and credits.
source and credits: http://www.geeksforgeeks.org
We have built the accelerating growth-oriented website for budding engineers and aspiring job holders of technology companies such as Google, Facebook, and Amazon
If you would like to study our free courses you can join us at

http://www.techcodebit.com. #techcodebit #google #microsoft #facebook #interview portal #jobplacements
#technicalguide

rakesh

Leave a Reply

Your email address will not be published. Required fields are marked *

Skip to toolbar