Java Reference
In-Depth Information
On the other hand, using integer or modular division would return a result
that separates hours and minutes, rather than the decimal result returned when
using regular division. First, integer division would drop the remainder, to result
in 2 hours:
integerAnswer = 168 / 60;
integerAnswer = 2;
Modular division, however, would keep only the remainder minutes, to
result in 48 minutes:
modulusAnswer = 168 % 60;
modulusAnswer = 48;
The operations of addition, subtraction, multiplication, and division shown
in Table 3-7 on the previous page can manipulate any data type. Dividing float
or double numbers will yield decimal results. If the operands in a division prob-
lem are of different data types, Java promotes the integers to floating point
values before evaluating the expression.
The integer and modular division operations can manipulate only integers.
As previously noted, Java performs integer division only on integer values and
drops the remainders in the resulting value. Java performs modular division only
on integers and stores the resulting remainder as an integer value. You will learn
about other special operators that involve single value arithmetic in a later
chapter.
A seventh operation, cast, also is listed in Table 3-7 because it performs a
kind of arithmetic on numbers. Sometimes programmers want to force data to
convert to a different data type. For example, for calculation or storage purposes,
an integer value might be forced to become a double, or the other way around.
The cast operation converts data from one primitive data type to another by
entering the new data type in parentheses before a literal or variable, as shown in
Table 3-7.
The ability to cast or convert primitive data types has some advantages. For
example, the program in Figure 3-16 calculates the average miles per gallon. The
user is asked to input miles and gallons. The input values are parsed in lines 16
and 20 to values that have been declared to be integers in line 9. The average
then is calculated by dividing the miles by the gallons (line 23). Normally Java
would return an int value because both values in the equation are integers. The
average variable, however, has been declared to be a double value. Without the
cast, the program would perform the operation on the right side first and would
store an integer value in average. With the cast (double) in line 23, the program
converts the total to a double before it performs the calculation, which increases
the precision of the answer. When Java performs math on mixed data types, the
result is always the larger data type. Therefore, when the program divides the
casted double named total by the integer named count, the result is a double that
subsequently is stored in the variable location named average.
Search WWH ::




Custom Search