Constants and the final Keyword

Contact Us or call 1-877-932-8228
Constants and the final Keyword

Constants and the final Keyword

Java has a means for defining contants, which are like variables in that they have names, but are not changeable once set.

If a variable is declared as final, it cannot be changed:

  • Even though the variable's value is not changeable once a value has been established, you are allowed to set a unique value once.
  • Local variables within methods may be declared as final.
  • Constants' values may be set in an explicit initialization, in a separate line of code, or, as method parameters passed when the method is called.
  • Fields within a class may be declared as final.
  • Contants' values may be set in an explicit initialization, in a separate line of code within an initialization block, or in a constructor.

Fields of a class may be declared as public static final - that way they are available to other classes, but cannot be changed by those other classes. An example is Math.PI.

Classes and methods may also be marked as final. We will cover this later.

Code Sample:

Java-Basics/Demos/FinalValues.java
public class FinalValues {

  // a constant
  final int scale = 100;
  
  // value below is dynamically created, 
  // but cannot change afterward
  final int answer = (int)(Math.random() * scale);
  
  public static void main(String[] args) {
    FinalValues fv = new FinalValues();
    System.out.println(fv.answer);
    
    // line below would not compile:
    // fv.answer = 44;
  }
}

The class has two final fields, scale and answer. The scale is fixed at 100, while the answer is initialized dynamically, but, once established, the value cannot be changed. Try removing the comment from the line that attempts to set it to 44, and you will see the compiler error message that results.

Next