• google plus

How to Use final Keyword in Java

The 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.

  1. Open your text editor and create a new file. Type in the following Java statements:
    Java Source for final Keyword
  2. The 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.

  3. Save your file as UsefinalKeywordInJava.java.

  4. 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.
    Compile Program with final Keyword with Error

  5. Return to your text editor and comment out the Java statement that caused the compile error.
    Compile Program with final Keyword
  6. Save your changes.

  7. In the command prompt, compile the corrected source code. Observe that the compile is now clean.
    Compile Program with final Keyword

  8. 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.
    Run Pogram with final Keyword
Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

About Webucator

Webucator provides instructor-led training to students throughout the US and Canada. We have trained over 90,000 students from over 16,000 organizations on technologies such as Microsoft ASP.NET, Microsoft Office, Azure, Windows, Java, Adobe, Python, SQL, JavaScript, Angular and much more. Check out our complete course catalog.