3.5 Compound Arithmetic Expressions | 115
to evaluate the expression in parentheses first, then divide the sum by double1, and multi-
ply the result by 3.0. Here are some more examples:
Expression Value
10 / 2 * 3 15
10 % 3 – 4 / 2 1
5.0 * 2.0 / 4.0 * 2.0 5.0
5.0 * 2.0 / (4.0 * 2.0) 1.25
5.0 + 2.0 / (4.0 * 2.0) 5.25
Type Conversion and Type Casting
Integer values and floating-point values are stored differently inside a computer’s memory.
The pattern of bits that represents the constant 2 , for example, does not look at all like the
pattern of bits that represents the constant 2.0. (In Chapter 12, we examine why floating-point
numbers need a special representation inside the computer.) What happens if we mix inte-
ger and floating-point values together in an assignment statement or an arithmetic ex-
pression? Let’s look first at assignment statements.
Assignment Statements If you make the declarations
int someInt;
doublesomeDouble;
then someIntcan hold onlyinteger values, and someDoublecan hold onlydouble-precision
floating-point values. The assignment statement
someDouble = 12;
may seem to store the integer value 12 into someDouble, but this is not true. The com-
puter refuses to store anything other than a doublevalue into someDouble. The
compiler inserts extra Bytecode instructions that first convert 12 into 12.0and then
store 12.0into someDouble. This implicit (automatic) conversion of a value from one
data type to another is known in Java as type conversion.
The statement
someInt = 4.8;
also causes type conversion. When a floating-point value is assigned to an intvariable, the
fractional part is truncated (cut off). As a result,someIntis assigned the value 4.
With both of the preceding assignment statements, the code would be less confusing for
someone to read if we avoided mixing data types:
someDouble = 12.0;
someInt = 4;
Type conversion The implicit
(automatic) conversion of a
value from one data type to an-
other