3

I am trying to understand what happens if I reassign a value to array element which is final, this is the code :

public class XYZ {
    private static final String[] ABC = {"Hello"};

    public static void main(String[] args){
        System.out.println(ABC[0]);

        ABC[0] = " World!!!";
        System.out.println(ABC[0]);

    }
}

ABC is final array and at first position it have "Hello" initially, but when I reassign it to " World!!!" it should either over ride the previous value or it should give compilation error for reassigning to final variable. This program runs fine and this is the output :

run:
Hello
 World!!!
BUILD SUCCESSFUL (total time: 0 seconds)
bigData
  • 1,318
  • 4
  • 16
  • 27
  • http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – kosa Sep 24 '14 at 21:51
  • @bigData use Collections.unmodifiableList(Arrays.asList(ABC)) to get an unmodifiable List and call toArray() to get the array at any point of time – Kumar Abhinav Sep 24 '14 at 21:59

4 Answers4

10

The final keyword does not mean you cannot change the state of the object, but only that the reference marked as final will remain constant. For example, you won't be able to do things like

final String[] ABC = {"Hello"};
ABC = new String[3]; // illegal
ABC = someOtherArray; // illegal;
ABC[0] = "World"; // legal
Dici
  • 25,226
  • 7
  • 41
  • 82
5

When final is applied to a variable, that only means that it cannot be reassigned once initialized. That does not prevent the object itself from being modified. In this case, you are modifying the array object. So this is fine:

ABC[0] = " World!!!";

But this would not have been allowed.

ABC = new String[]{" World!!!"};
rgettman
  • 176,041
  • 30
  • 275
  • 357
5

Arrays are mutable Objects unless created with a size of 0.Therefore,you can change the contents of an array.final only allows you to prevent the reference from being changed to another array Object.

final String[] ABC ={"Hello"};
ABC[0]="Hi" //legal as the ABC variable still points to the same array in the heap
ABC = new String[]{"King","Queen","Prince"}; // illegal,as it would refer to another heap Object

I suggest you use Collections.unmodifiableList(list) to create a immutable List.See the javadoc here (unmodifibale list).

You can do the following

String[] ABC = {"Hello"};
List<String> listUnModifiable = Collections.unmodifiableList(java.util.Arrays.asList(ABC));

At any point of time,you can get the array by calling listUnModifiable.toArray();

Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35
1

My response is same as the others that "final" only prevents the variable from pointing to a new object, it does not prevent the object itself updates its members.

Additional response about you mention that the output seems to append the string, but it is not, because you have a print statement before the assignment, and one after the assignment.