A parameter to a function can be declared with the keyword final. This indicates that the parameter cannot be modified in the function. The final keyword can allow you to make a variable a constant.
You might want to pass an array but ensure that the method doesn't modify the array.
Example of using final:
public static void f(final int var) {
System.out.println(var);
}
This method ensures that the user cannot modify var. If the user tries then an error occurs.
You can call this method just like any other method. The key here is that the var variable cannot be modified.
Let us try to modify the variable.
Change the function to:
public static void f(final int var) {
System.out.println(var++);
}
If I try to compile this code and call this method then a RuntimeException is thrown. However, this might not be easy to find. You may accidentally modify the variable in the method without realizing it. The nice thing is Netbeans won't compile my program with this error.
It will just say:
Quote
final parameter var may not be assigned
However, it is worth to note that you can do this:
public static void f(final int var) {
System.out.println(var+1);
}
This isn't modifying the variable.
Final Array
We can declare an array to be final. Let us take a look at what final does with an array.
public static void f(final int[] arr){
arr[2]++;
}
Call the method with this code:
int[] arr = {3,2,5,4};
f(arr);
Do you think the program will compile, or will it throw a RuntimeException?
It actually will compile. The program isn't modifying the array. It is modifying an item in the array. However, trying to allocate a new array will throw an error.
E.g.
public static void f(final int[] arr){
arr = new int[7];
}
This will throw the RuntimeException.
The final keyword is great if you want to ensure that you do not modify a variable when you pass it to a function. You can also use it with class variables. This is similar to using const in C++.
Final Variables
Similarly, a variable can be declared final. You can also declare classes as final (meaning that they cannot be extended).
Example:
public final int X = 5;


Sign In
Create Account


Back to top









