Page 107 - Introduction to Programming with Java: A Problem Solving Approach
P. 107
An Example
Let’s put what you’ve learned about constants into practice by using them within a complete program. In Figure 3.5’s TemperatureConverter program, we convert a Fahrenheit temperature value to a Celsius temper- ature value. Note the two named constant initializations at the top of the program: (1) the FREEZING_POINT named constant gets initialized to 32.0 and (2) the CONVERSION_FACTOR named constant gets initialized to 5.0 / 9.0. Usually, you’ll want to initialize each named constant to a single hard-coded constant. For example, FREEZING_POINT’s initialization value is 32.0. But be aware that it’s legal to use a constant expression for a named constant initialization value. For example, CONVERSION_FACTOR’s initialization value is 5.0 / 9.0. That expression is considered to be a constant expression because constant values are used, not variables.
3.14 Constants 73
/***********************************************************************
*
TemperatureConverter.java
Dean & Dean
This program converts a Fahrenheit temperature to Celsius
***********************************************************************/
*
*
*
public class TemperatureConverter
{
}
// end class TemperatureConverter
public static void main(String[] args)
{
}
celsius = CONVERSION_FACTOR * (fahrenheit - FREEZING_POINT);
System.out.println(fahrenheit + " degrees Fahrenheit = " +
celsius + " degrees Celsius.");
// end main
Apago PDF Enhancer
final double CONVERSION_FACTOR = 5.0 / 9.0;
final double FREEZING_POINT = 32.0;
double fahrenheit = 50;
double celsius;
// temperature in Fahrenheit
// temperature in Celsius
Output:
50.0 degrees Fahrenheit = 10.0 degrees Celsius.
Figure 3.5 TemperatureConverter program and its output
In the TemperatureConverter program, this statement performs of the conversion:
celsius = CONVERSION_FACTOR * (fahrenheit - FREEZING_POINT);
By using named constants, CONVERSION_FACTOR and FREEZING_POINT, we’re able to embed some meaning into the conversion code. Without named constants, the statement would look like this:
celsius = 5.0 / 9.0 * (fahrenheit - 32.0);
The 5.0 / 9.0 may be distracting to some readers. They may spend time wondering about the significance of the 5.0 and the 9.0. By using a CONVERSION_FACTOR named constant, we tell the reader “Don’t