Arithmetic Promotion, Assignments, and Casting

In an assignment statement, i.e. if there's an equals sign, Java compares the type of the left hand side to the final type of the right hand side. It won't change the type of the left hand side, but it will check to make sure that the value it has (double, float, int or long) on the right hand side can fit in the type on the left hand side. Anything can fit in a double. Anything except a double can fit in a float. Any integral type can fit in a long, but a float or a double can't, and ints, shorts, and bytes can fit inside ints. If the right hand side can fit inside the left hand side, the assignment takes place with no further ado.

Assigning long values to int variables or double values to float variables can be equally troublesome. In fact it's so troublesome the compiler won't let you do it unless you tell it you really mean it with a cast. When it's necessary to force a value into a particular type, use a cast. To cast a variable or a literal or an expression to a different data type just precede it with the type in parentheses. For instance:

int i = (int) (9.0/4.0);

A cast lets the compiler know that you're serious about the conversion you plan to make.

When a value is cast down before assignment, series of operations takes place to chop the right hand side down to size. For a conversion between a floating point number and an int or a long, the fractional part of the floating point number is truncated (rounded toward zero). This produces an integer. If the integer is small enough to fit in the left hand side, the assignment is completed. On the other hand if the number is too large, then the integer is set to the largest possible value of its type. If the floating point number is too small the integer is set to the smallest possible value of its type.

This can be a nasty bug in your code. It can also be hard to find since everything may work perfectly 99 times out of a hundred and only on rare occasions will the rounding become a problem. However when it does there will be no warning or error message. You need to be very careful when assigning floating point values to integer types.


Previous | Next | Top | Cafe au Lait

Copyright 1997, 1999, 2003 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified September 12, 2003