Page 105 - Introduction to Programming with Java: A Problem Solving Approach
P. 105
3.14 Constants
We’ve used numeric and string values in our examples, but we haven’t given you the formal name for them. Numeric and string values are called constants. They’re called constants because their values are fixed— they don’t change. Here are some examples:
Integer Constants
8
-45
2000000
Floating-Point Constants
-34.6
.009
8.
String Constants
"Hi, Bob"
"yo"
"dog"
For a constant to be a floating-point constant, it must contain a decimal point, but numbers to the right of the decimal point are optional. Thus, 8. and 8.0 represent the same floating-point constant.
What is the default type for integer constants—int or long? You’d probably guess int since integer sounds like int. And that guess is correct — the default type for an integer constant is int. So the above integer examples (8, 45, and 2000000) are all int constants.
What is the default type for floating-point constants—float or double? Although you might be tempted to say float, after the discussion in the previous section, it should not surprise you that Java’s default for floating-point constants is double.
Try to identify the compile-time errors in this code fragment:
float gpa = 2.30;
float mpg;
mpg = 28.6;
Apago PDF Enhancer
The 2.30 and 28.6 constants both default to type double, which uses 64 bits. The 64 bits can’t squeeze into the 32-bit gpa and mpg variables so this code generates “possible loss of precision” error messages.
There are two possible solutions for these types of errors. The easiest solution is to use double variables instead of float variables all the time. Here’s another solution: Explicitly force the floating-point constants to be float by using an f or F suffix, like this:
float gpa = 2.30f;
float mpg;
mpg = 28.6F;
Two Categories of Constants
Constants can be split into two categories—hard-coded constants and named constants. The constants we’ve covered so far can be referred to as hard-coded constants. A hard-coded constant is an explicitly specified value. Hard-coded constants are also called literals. “Literal” is a good, descriptive term because literals refer to items that are interpreted literally; for example, 5 means 5, “hello” means “hello.” In the following statement, the forward slash (/) is the division operator, and 299792458.0 is a hard-coded constant (or literal):
propagationDelay = distance / 299792458.0;
Assume that this code fragment is part of a program that calculates delays in messages carried through space. What’s the meaning behind the value 299792458.0? Not very obvious, eh? Read on.
In space, message signals travel at the speed of light. Since time distance / velocity, the time it takes a message signal to travel from a satellite equals the satellite’s distance divided by the speed of light. Thus, in the code fragment, the number 299792458.0 represents the speed of light.
3.14 Constants 71
Use a larger data type