Way2Java

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.

public class Conversions
{
  public static void main(String args[])
  {
    int i1 = 10;                  // 4 bytes
    // short s1 = i1;             // error, 4 bytes to 2 bytes
          
    short s1 = (short) i1;        // int is explicit type converted to short

    System.out.println("int value: " + i1);                 // prints 10    
    System.out.println("Converted short value: " + s1);     // prints 10
  }
}



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