
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.
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.
double, the other one will be converted to a double.
float, the other one will be converted to a float.
long, the other one will be converted to a long.
int.
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:
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: