Previous | Home | Next |
In java there are two type of conversions between numeric types:
- Widening primitive conversion and
- Narrowing Primitive conversion
These conversions are applying for integers
Widening primitive Conversion:
Narrowing Primitive Conversion:
Widening conversion are very simple. There is no cast required and will never result in a runtime exception. precision may be lost when converting from integer to floating point types.
byte | to | short, int, long, float, or double |
short | to | int, long, float, or double |
char | to | int, long, float, or double |
int | to | long, float, or double |
long | to | float or double |
float | to | double |
Example :
int i = 65; long l = i; class WideningConversion { public static void main(String[] args) { int i = 123456789; float f = i; System.out.print(f); } }
Output :
1.23456792E8
Cast required between types. Overflow and underflow may happen but a runtime exception will never happen. In case of narrowing conversion from long (64 bit) to int (32) bit we have 32 fewer bits in the destination number. The following integer type conversions are the narrowing ones.
short | to | byte or char |
char | to | byte or short |
int | to | byte, short, or char |
long | to | byte, short, char, or int |
float | to | byte, short, char, int, or long |
double | to | byte, short, char, int, long, or float |
Example :
long l = 656666L; int i = (int) l;
Previous | Home | Next |