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:
- If one of the operands is a double, the other operand is converted
into a double,
- else if one of the operands is a float, the other operand is converted
into a float,
- else if one of the operands is a long, the other operand is converted
into a long,
- else both operands are converted to an int.
Representation of Numeric Constants
- The default datatype for an integer constant is an int.
- To force the datatype for an integer constant to be a long,
use an L after the constant. For example, 153L.
- The default datatype for a floating point constant is a double.
- To force the datatype for an floating point constant to be a float,
use an F after the constant. For example, 3.14159F.