How to Use final Keyword in Java
final keyword can be used to declare a variable as a constant in Java. To use
final keyword to declare a constant, follow these seven steps.
- Open your text editor and create a new file. Type in the following Java statements:
- Save your file as UsefinalKeywordInJava.java.
- Open a command prompt and navigate to the directory containing your new Java program. Then type in the command to compile your program and hit Enter. Notice the compile error, underscored with the red line.
- Return to your text editor and comment out the Java statement that caused the compile error.
- Save your changes.
- In the command prompt, compile the corrected source code. Observe that the compile is now clean.
- Now you will run your Java program. Type in the command to run the Java runtime launcher and hit Enter. Notice the value of your constant in the program's output.
final keyword is coded before the data type declaration. Once a value is assigned, the value of the variable cannot be changed. Therefore, the statement highlighted in the red, rounded rectangle will fail compilation.