This Java video tutorial examines the uses of declared constants in Java. Declared constants are related to variables and literal values. However, they have distinct advantages when a constant value is used multiple times at many different places in a program.
Advantages Over Variables
- Enforce Constancy
- Allow For Optimization
With respect to variables, declared constants have two distinct advantages. First, they enforce constancy so that the programmer knows that the value will not be accidentally changed by him or another programmer; in this way, constants can help to catch bugs and make code more stable. Second, constants allow the compiler to optimize for memory and speed by allowing the compiler to replace the declared constant by a simple literal value; this can be done by the compiler, since it knows that the value will remain constant.
Advantages Over Literals
- Facilitate Changes
Declared constants also offer some advantages over literal values. First, the use of names for constant values makes code more readable; for example, iX = kiHoursPerDay*kiDaysPerWeek is much clearer than iX = 24*7. Second, constants create consistency for approximations accross the code base; using a constant like kiSqrt2 = 1.414 throughout the code means that you will not have one programmer using the value 1.414 as an approximation and another using 1.41421. Lastly, constants allow us to make changes across the entire code base with one simple change and a recompilation; imagine using a literal value of, say 18, for the voting age in many places across a large code base and then having the law change to 19. With numerous literals, it would be extremely messy and error prone.
Declaration of a Constant
final int kiOuncesPerCup = 8;
A constant is declared just like a variable of the same type, except that we put the word final in the front of the declaration. The word final signifies that the value will not be changed, so it should be initilized in the declaration. We use a declared constant when we have a known value that is not going to change and will be used in many different places in the code, like the number of ounces in a cup.
final int kiOuncesPerCup = 8; System.out.println("4 cups equals " + 4*kiOuncesPerCup + " ounces");
Above, we have created a constant to convert between ounces and cups. In the second line, we output the conversion of four cups into ounces. If we put this code into a default project and compile and execute it, we see this in the output pane.