From Core Java, Volume 1 Fundamentals, Chapter 3


Figure 3-1:Legal Conversions between numeric types

The six black arrows in Figure 3-1 denote conversions without information loss. The three grey arrows denote conversions that may lose precision. For example, a large integer such as 123456789 has more digits than the float type can represent. When converting it to a float, the resulting value has the correct magnitude, but it loses some precision.

int n = 123456789; float f = n; // f is 1.23456792E8

When combining two values with a binary operator (such as n + f where n is an integer and f is a floating-point value), both operands are converted to a common type before the operation is carried out.

Casts

In the preceding section, you saw that int values are automatically converted to double values when necessary. On the other hand, there are obviously times when you want to consider a double as an integer. Numeric conversions are possible in Java, but of course information may be lost. Conversions where loss of information is possible are done by means of casts. The syntax for casting is to give the target type in parentheses, followed by the variable name. For example:

double x = 9.997; int nx = (int)x; Then, the variable nx has the value 9, as casting a floating-point value to an integer discards the fractional part.

If you want to round a floating-point number to the nearest integer (which is the more useful operation in most cases), use the Math.round method:

double x = 9.997; int nx = (int)Math.round(x); Now the variable nx has the value 10. You still need to use the cast (int) when you call round. The reason is that the return value of the round method is a long, and a long can only be assigned to an int with an explicit cast since there is the possibility of information loss.