(^116) | Arithmetic Expressions
(^1) In non-Java terminology, implicit conversions are called coercionsand explicit conversions are called casts.
More often, it is not just constants but entire expressions that are involved in type con-
version. For example, both of the assignments
someDouble = 3 someInt + 2;
someInt = 5.2 / someDouble – anotherDouble;
lead to type conversion. Storing the result of an intexpression into a doublevari-
able doesn’t cause loss of information; a whole number such as 24 can be repre-
sented in floating-point form as 24.0. In the Java language, a type conversion that
does not result in a loss of information is known as a widening conversion. Assigning
intvalues to longvariables or floatvalues to doublevariables are also examples
of widening conversions.
However, storing the result of a floating-point expression into an intvariable
can cause a loss of information because the fractional part is truncated. Java refers
to such a conversion as a narrowing conversion. It is easy to overlook the assign-
ment of a floating-point expression to an intvariable, a doublevalue to a floatvari-
able, or a longvalue to an intvariable when we try to discover why our code is
producing the wrong answers.
To make our code as clear (and error-free) as possible, we should use explicit
type casting. A Java cast operationconsists of a data type name within parentheses,
followed by the expression to be converted:
someDouble = (double)(3 someInt + 2);
someInt = (int)(5.2 / someDouble – anotherDouble);
Both of the statements
someFloat = someInt + 8;
someFloat = (float)(someInt + 8);
produce identical results; the only difference is in their clarity. With the cast operation, it is per-
fectly clear to the programmer and to others reading the code that the mixing of types is in-
tentional, not an oversight. Countless errors have resulted from unintentional mixing of types.
There is a nice way to round off rather than truncate a floating-point value before stor-
ing it into an intvariable:
someInt = (int)(someDouble + 0.5);
With pencil and paper, see for yourself what gets stored into someIntwhen someDoublecon-
tains 4.7. Now try it again, assuming someDoublecontains 4.2. (This technique of rounding by
adding 0.5 assumes that someDoubleis a positive number.)
Widening conversion A type
conversion that does not result
in a loss of information^1
Narrowing conversion A type
conversion that may result in a
loss of some information, as in
converting a value of type
doubleto typefloat
Type casting The explicit con-
version of a value from one data
type to another
やまだぃちぅ
(やまだぃちぅ)
#1