int to short Java

int to short Java

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

The int takes 4 bytes of memory and short takes 2 bytes of memory. Assigning 4 bytes of memory to 2 bytes goes by explicit casting where Programmer should do by himself.

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 int to short requires explicit casting.

Examples of implicit casting

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

byte x = 10; // 1 byte
short y = x; // 1 byte to 2 bytes

Following program explains explicit casting with int to short. Observe, the Java style of explicit casting.


int to short
Output screenshot of int to short Java

short s1 = i1;

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

short s1 = (short) i1;

The int i1 is explicitly type casted to short s1. Observe, the syntax of explicit casting. On both sides, it should be short.

View all for 65 types of Conversions

Leave a Reply

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