AP Computer Science Java: Lesson 1.5c
Math Operations - Mixing Data Types

Lesson 1.5c - Mixing Data Types
Purpose: To learn how Java handles math operations on integers and decimals

Integers vs. Doubles
We have already seen various scenarios where integers and decimals interact with each other. A little more discussion is necessary in order to truly understand how this works. A few starting points:

1. When integers interact with integers, the result is always integer.
When decimals interact with decimals, the result is always decimal.
When integers and decimals interact, the result will always be in decimal form.

Let's see some examples. Assume the following declarations:

   int intt;  double dub;

A Sampling of Mixed-Mode Arithmetic
intt = 3 + 2;
dub = 3 + 2;
intt = 5
dub = 5.0
dub gets the decimal version of 5
intt = 3.2 + 2.5;
dub = 3.2 + 2.5;
intt = error
dub = 5.7
intt can't receive a decimal value - this is a loss of precision error
intt = 3.2 + 2;
dub = 3.2 + 2;
intt = error
dub = 5.2
intt can't receive a decimal value - this is a loss of precision error
intt = 3 + 2.5;
dub = 3 + 2.5;
intt = error
dub = 5.5
intt can't receive a decimal value - this is a loss of precision error
intt = 3 / 2;
dub = 3 / 2;
intt = 1
dub = 1.0
intt and dub both get the truncated value of 1.5, dropping the decimal to get 1

Division with Integers
The last example requires further analysis. The rule to remember is that integers mixing with integers results in an integer. Even though the result is stored in a double, it is a truncated integer before it is stored.

So how cane we get the correct decimal answer when dividing integers? Below are two ways to accomplish that. Assume the variable declarations given.

int int1, int2; double quotient;
quotient = 1.0 * int1 / int2;
quotient = (double) int1 / int2; //NOT (double) (int1 / int2);

The first example multiplies the numerator by a decimal, creating a decimal divided by an int, therefore resulting in a decimal.

The second example makes use of typecasting, temporarily assigning or casting an int value as a double. Note the use of parentheses around the keyword double.

More with Typecasting Typecasting can also enable a decimal value to be stored in an int variable, as a truncated integer. Recall the loss of precision errors from above when attempting to store a decimal in an int. If we typecast, as follows

    intt = (int)(3.2 + 2.5);

the result is that intt will contain 5, the truncated form of 5.7. This technique can be used in problem 12, when we want to round down to the nearest integer.

© DanShuster.com