The following code in Java uses a final
array of String
and there is no question about it.
final public class Main { public static final String[] CONSTANT_ARRAY = {"I", "can", "never", "change"}; public static void main(String[] args) { for (int x = 0; x < CONSTANT_ARRAY.length; x++) { System.out.print(CONSTANT_ARRAY[x] + " "); } } }
It displays the following output on the console.
I can never change
The following code also goes without any question.
final public class Main { public static final String[] CONSTANT_ARRAY = {"I", "can", "never", "change"}; public static void main(String[] args) { //CONSTANT_ARRAY={"I", "can", "never", "change"}; //Error - can not assign to final variable CONSTANT_ARRAY. for (int x = 0; x < CONSTANT_ARRAY.length; x++) { System.out.print(CONSTANT_ARRAY[x] + " "); } } }
Obviously, the commented line causes the specified error because we are trying to reassign the declared final
array of type String
.
What about the following code.
final public class Main { public static final String[] CONSTANT_ARRAY = {"I", "can", "never", "change"}; public static void main(String[] args) { CONSTANT_ARRAY[2] = "always"; //Compiles fine. for (int x = 0; x < CONSTANT_ARRAY.length; x++) { System.out.print(CONSTANT_ARRAY[x] + " "); } } }
and it displays I can always change
means that we could manage to modify the value of the final
array of type String
. Can we ever modify the entire array in this way without violating the rule of final
?
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 the array can be modified.
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. However, the data within the object can be changed.
If you declare a final variable later on you cannot modify or, assign values to it.
You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final .
final
in Java affects the variable, it has nothing to do with the object you are assigning to it.
final String[] myArray = { "hi", "there" }; myArray = anotherArray; // Error, you can't do that. myArray is final myArray[0] = "over"; // perfectly fine, final has nothing to do with it
Edit to add from comments: Note that I said object you are assigning to it. In Java an array is an object. This same thing applies to any other object:
final List<String> myList = new ArrayList<String>(): myList = anotherList; // error, you can't do that myList.add("Hi there!"); // perfectly fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With