long to short java

long to short java

After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast long to short as an example.

The long takes 8 bytes of memory and short takes 2 bytes of memory. Assigning 8 bytes of memory to 2 bytes of memory requires explicit casting. It is like not possible to pour bigger bottle water into a smaller bottle.

byte –> short –> int –> long –> float –> double

The left-side value can be assigned to any right-side value and is done implicitly. The reverse like long to short requires explicit casting.

Examples of implicit casting

short x = 10; // 2 bytes
int y = x; // 2 bytes to 4 bytes

byte x = 10; // 1 byte
int y = x; // 1 byte to 4 bytes

Following program on long to short explains explicit casting. Observe, Java style syntax where long is type explicitlly converted to short.

long to short
Output screenshot of long to short Java

short s1 = l1;

The above statement raises a compilation error "possible loss of precision" as 8 bytes value is assigned to 2 bytes and requires explicit casting.

short s1 = (short) l1;

The long l1 is explicitly type casted to short s1. Observe, the syntax of explicit casting. On both sides, it should be short. This is known as narrowing conversion.

View all for 65 types of Conversions

Leave a Reply

Your email address will not be published. Required fields are marked *