short to long Java

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

The short takes 2 byte of memory and long takes 8 bytes of memory. Assignment 2 bytes of memory to 8 byte of memory is done implicitly. This is known as widening conversion. This is like pouring smaller bottle water in a bigger bottle.

See the data types order to know the brief rules of casting.

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;
   int y = x;

   byte x = 10;
   short y = x;
Following example on short to long explains the Java syntax where a short value is implicitly assigned to a long value.
public class Conversions
{
  public static void main(String args[])
  {
    short s1 = 10;              // 2 bytes
    long l1 = s1;               // 2 bytes assigned to 8 bytes

    System.out.println("short value: " + l1);              // prints 10
    System.out.println("Converted long value: " + l1);     // prints 10
  }
}


short to long
Output screenshot of short to long Java

    long 11 = s1;

The short s1 is assigned to long l1. This is done implicitly by JVM.

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.