Type Conversion in Java
Widening Type Conversion
- Smaller Data Type -> Larger Data Type
- •Larger Data Type -> Smaller Data Type
Conversion done in two ways
- –Implicit type conversion
- •Carried out by compiler automatically
- –Explicit type conversion
- •Carried out by programmer using casting
Widening Type Converstion
Implicit conversion by compiler automatically
byte -> short, int, long, float, double
short -> int, long, float, double
char -> int, long, float, double
int-> long, float, double
long -> float, double
float -> double
- byte and short are always promoted to int
- if one operand is long, the whole expression is promoted to long
- if one operand is float, the entire expression is promoted to float
- if any operand is double, the result is double
Examples:
1) integer value will be reduced module bytes range:
- int i;
- byte b = (byte) i;
2) floating-point value will be truncated to integer value:
- float f;
- int i = (int) f;