To Documents

Java Conversions and Casts

Automatic Conversion and the Cast Operator

The cast operator in Java converts one datatype to another. For example, x = (int) y converts the value of y into an integer and stores the result in x. In some cases, the conversion is performed automatically without an explicit cast, as in this example: x = y

The following diagram indicates the legal conversions that do not lose information).
       char
       ¯
byte ® short ® int ® long
       ¯
       double
These conversions are legal and do not lose information. The conversion float ® double is also legal and does not lose information. The conversions int ® float, long ® float, and long ® double are also legal but might undergo a loss of precision.

The conversions in the following diagram are dangerous, because high order bits might be trucated, so information may be lost:

byte ¬ short ¬ int ¬ long ¬ single ¬ double

These conversions require an explicit casts. Casts that cause information loss will not result in compiler or runtime error messages, but will result in wrong output.

Conversion in Expressions

When an arithmetic expression is performed on different datatypes, the following conversions are performed:

Representation of Numeric Constants