Java Reference
In-Depth Information
of an operand by a process called type casting . Implicit conversions are
performed automatically by the language.
Implicit conversions
Java performs implicit conversions between numeric types only if no loss
of precision or magnitude results from the conversion. In the case of unary
conversions, operands of type byte and short are automatically converted
to type int. All other types are preserved. In the case of binary conversions
the rules are as follows:
1. With integer types, if one of the operands is long, then the other one is con-
verted to long. Otherwise, both operands are converted to int.
2. Also in relation to integers, the expression is an int except if the value is too
long for the int format. In this case the value is converted to a long.
3. For operations on floating-point types, if one operand is a double, the other
one is also converted to double and the result is of type double. Otherwise,
both operands are converted to float and the result is a float type.
Type-casting
Explicit conversions are performed by a process called casting or type
casting. Type casting consists of preceding the operand with the desired
type, enclosed in parentheses. Recall the case of the gas flow valve men-
tioned at the beginning of this section. Here we needed to convert two inte-
ger variables to a floating-point type. In this case the cast can be as follows:
int maximumFlow = 10;
int flowSetting = 5;
double flowRate;
...
flowRate = (double) maximumFlow / (double) flowSetting;
The variable flowRate now has the expected ratio of 0.5.
Java type casting must follow the following rules:
1. Boolean variables cannot be cast into any other type.
2. Any of the integer data types can be cast into any other type, except
boolean. Casting into a smaller type can result in loss of data.
3. Floating-point types can be cast into other float types or into integer types.
These casts may result in loss of data.
4. The char type can be cast into integer types. Since the char is 16-bits wide,
casting into a byte type may result in loss of data or in garbled characters.
Search WWH ::




Custom Search