Java Tutorial/Language/Constant

Материал из Java эксперт
Перейти к: навигация, поиск

Define a constant value and use it

  1. Using the final keyword to declare a variable.
  2. The final keyword specifies that the value of a variable is final and cannot be changed.
  3. It is a convention in Java to write constants in uppercase letters.



public class MainClass {
  public static void main(String[] arg) {
    final int FEET_PER_YARD = 3;          // Constant values
    final double MM_PER_INCH = 25.4;      // that cannot be changed
    System.out.println(FEET_PER_YARD);
    System.out.println(MM_PER_INCH);
    
  }
}



3
25.4


Define constant

"public static final" variables are constant.

The naming convention for static final variables is to have them in upper case and separate two words with an underscore. For example:



static final int NUMBER_OF_MONTHS = 12;
static final float PI = (float) 22 / 7;