Constants: final
A final variable is a constant
Once its value has been set, it cannot be changed
Named constants make programs easier to read and maintain
Convention: use all-uppercase names for constants
final double QUARTER_VALUE = 0.25;
final double DIME_VALUE = 0.1;
final double NICKEL_VALUE = 0.05;
final double PENNY_VALUE = 0.01;
payment = dollars + quarters * QUARTER_VALUE
+ dimes * DIME_VALUE + nickels * NICKEL_VALUE
+ pennies * PENNY_VALUE;
Constants: static final
If constant values are needed in several methods, declare them together with the instance fields of a class and tag them as static and final
Give static final constants public access to enable other classes to use them
public class Math
{
. . .
public static final double E = 2.7182818284590452354;
public static final double PI = 3.14159265358979323846;
}
double circumference = Math.PI * diameter;
Example: Click the following files