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.
public class Conversions
{
  public static void main(String args[])
  {
    long l1 = 10;            // 8 bytes
    // short s1 = l1;        // error, 8 bytes long to 2 bytes short
          
    short s1 = (short) l1;   // 8 bytes long is type converted to 2 bytes short
    
    System.out.println("long value: " + l1);               // prints 10
    System.out.println("Converted short value: " + s1);    // prints 10
  }
}


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 Comment

Your email address will not be published.