Conversions between Numeric Types in Java Programming

Conversions between Numeric Types in Java Programming

Previous Home Next

 

In java there are two type of conversions between numeric types:

1.Widening primitive conversion and
2.Narrowing primitive conversion

These conversions are applying for integers.

Widening conversions are very simple. 
Since we get more space and there is always the most significant bit reserved for the sign.
we just put some 0s in the unused bit positions and copy the sign bit from the original number.
Thus, in case of widening conversion we never lose anything this is true for the integer numbers only.

following are the widening conversions:
 byte to short, int, long
 short to int, long
 char to int, long
 int to long

 A narrowing numeric conversion can result in a value of different sign, a different order of magnitude, or both
 it may thereby lose precision.
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



 


 

Previous Home Next