Previous | Next | Trail Map | Writing Java Programs | Java Objects


Declaring a Constant

To create a constant in Java use the keyword final in your variable declaration. The following variable declaration defines a constant named AVOGADRO whose value is Avogadro's number (6.023 x 10^23) and cannot be changed.
final double AVOGADRO = 6.023e23;
By convention, names of constant values are spelled in all capital letters. If your program ever tries to change a constant, the compiler will display an error message similar to the following, and refuse to compile your program.
AvogadroTest.java:5: Can't assign a value to a final variable: AVOGADRO


Previous | Next | Trail Map | Writing Java Programs | Table of Contents