In Java, the final
keyword is used to indicate that a variable is a constant and cannot be reassigned.
Here's an example of how to use the final
keyword with a variable:
public class Main { public static void main(String[] args) { final int constant = 42; System.out.println(constant); // prints "42" // The following line would generate a compile-error because it attempts to reassign a final variable // constant = 50; } }
Declaring a variable as final
can be useful in cases where you want to ensure that the value of the variable cannot be changed. This can be especially important if the variable is used in multiple places in your code and you want to ensure that it has a consistent value.
Note that you can also declare a method parameter as final
, which means that the value of the parameter cannot be changed within the method.
You can find more information about the final
keyword in the Java documentation.