Java Reference
In-Depth Information
Sample Run:
3 / 2 + 5.0 = 6.0
15.6 / 2 + 5 = 12.8
4 + 5 / 2.0 = 6.5
4 * 3 + 7 / 5 - 25.5 = -12.5
2
These examples illustrate that an integer is not treated as a floating-point number unless
the operator to be evaluated has one integer and one floating-point operand.
Type Conversion (Casting)
In the previous section, you learned that when evaluating an arithmetic expression if the
operator has mixed operands, the integer value is treated as a floating-point value with the
zero decimal part. When a value of one data type is automatically treated as another data
type, an implicit type coercion has occurred. As the examples in the preceding section
illustrate, if you are not careful about data types, implicit type coercion can generate
unexpected results.
To avoid implicit type coercion, Java provides for explicit type conversion through the
use of a cast operator. The cast operator, also called type conversion or type casting,
takes the following form:
(dataTypeName) expression
First, the expression is evaluated. Its value is then treated as a value of the type specified
by dataTypeName .
When using the cast operator to treat a floating-point (decimal) number as an integer,
you simply drop the decimal part of the floating-point number. That is, the floating-point
number is truncated. The following examples show how cast operators work. Be sure
you understand why the last two expressions evaluate as they do.
EXAMPLE 2-8
Expression
Evaluates to
( int )(7.9)
7
( int )(3.3)
3
( double )(25)
25.0
( double )(5 + 3)
= ( double )(8) = 8.0
= 15.0 / 2 (because ( double )(15) = 15.0 )
= 15.0 / 2.0 = 7.5
( double )(15) / 2
 
 
Search WWH ::




Custom Search