0

I have a relatively simple question regarding the function of final in Java. When I compile this code:

import java.util.*;
import java.lang.*;
import java.io.*;


class Arrays
{
 public static void main (String[] args) throws java.lang.Exception
 {
final int[] myArray = { 1,2 }; 
myArray[1] = 3; 
System.out.println (myArray[1]);  
 }
}

The number "3" gets printed. However, I was under the impression that final meant that the values held in that array (myArray) can no longer change and are constant.

There is also another piece of code here:

final int [] a1 = {1, 2}; 
int [] b1 = {3, 4};
a1 = b1; System.out.println (a1[1]);

I believe that the system should print "2" since a1 is finalized and the values in the array are constant. However, my friend believes that it should be "4". Please help me clear up my understanding of final.

Raceimaztion
  • 9,494
  • 4
  • 26
  • 41
Javasaurus
  • 19
  • 1
  • 1
  • 4
  • Does this answer your question? [Why can I edit the contents of a final array in Java?](https://stackoverflow.com/questions/10339930/why-can-i-edit-the-contents-of-a-final-array-in-java) – TylerH Aug 19 '22 at 18:26

4 Answers4

2

An int[] is an object type (not a primitive and not an int). The final reference means you can't reassign the reference when referring to an Object instance.

final int [] a1 = {1, 2}; 
a1 = {3,4}; // <-- illegal, a1 is final.

In fact, Java is making the value final in both cases (the value of an Object is its' reference).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Final means a value cannot be changed. But when int[] myArray; is declared then myArray holds the reference of the array and not the values. So the statement, myArray[1] = 3; changes the contents at that position because it is not declared as final. and the statement myArray = (any value); is illegal since we are changing the reference which is declared as final.

0

When you define a variable as final you cannot reassign it to another value.

final int a = 2;
a = 5; \\ error

similarly, when you use a final array:

final int[] arrA = {1,2,3};
arrA = new int[]{4, 5, 6}; \\ error

But you can always change the values inside the array, as they are not final. Therefore it seems like your second example will not compile. If you do not want to change the values inside an array then you are better off with enum.

Sourabh Bhat
  • 1,793
  • 16
  • 21
0

A final modifier declares the variable cannot change. However, object/array variables are really just handles to unnamed objects/arrays. Since the value of a object variable is a handle, it ensures the handle cannot change. The array on the other end of that handle has nothing to do with final at all.

 final int myInt = 5; //myInt cannot change (5 is the value of myInt)
 final int[] myArr = {1,2};
 myArr[0] = 3; //legal. myArr is a handle to a int[] and we're not modifying the handle
Kitten
  • 437
  • 3
  • 13