The value of a variable may change during the execution of the program, but a constant represents permanent data that never changes. In our ComputeArea program, is a constant. If you use it frequently, you don't want to keep typing 3.14159 ; instead, you can define a constant for Here is the syntax for declaring a constant:
final datatype CONSTANTNAME = VALUE;
A constant must be declared and initialized in the same statement. The word final is a Java keyword which means that the constant cannot be changed. For example, in the ComputeArea program, you could define p as a constant and rewrite the program as follows :
// ComputeArea.java: Compute the area of a circle public class ComputeArea { /** Main method */ public static void main(String[] args) { final double PI = 3.14159 ; // Declare a constant // Assign a radius double radius = 20 ;
// Compute area double area = radius * radius * PI ; // Display results System.out.println( "The area for the circle of radius " + radius + " is " + area); } }
Caution
By convention, constants are named in uppercase: PI , not pi or Pi . |
Note
There are three benefits of using constants: (1) you don't have to repeatedly type the same value; (2) the value can be changed in a single location if necessary; (3) a descriptive name for a constant makes the program easy to read. |