short to byte Java

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

The byte takes 1 byte of memory and short takes 2 bytes of memory. Assigning 2 bytes of memory to 1 byte of memory requires explicit casting. This is known as narrowing conversion.

See the order of data types to know the 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 short to byte requires explicit casting.

Examples of implicit casting

short x = 10;
int y = x;

byte x = 10;
short y = x;

Following program explains explicit casting, Java style where a short is assigned to byte.

public class Conversions
  public static void main(String args[])
    short s1 = 10;
    // byte b1 = s1;  
    byte b1 = (byte) s1;   // observe syntax of Java explicit casting

    System.out.println("short value: " + b1);              // prints 10
    System.out.println("Converted byte value: " + b1);     // prints 10

short to byte
Output screenshot of short to byte Java

byte b1 = s1;

The above statement raises a compilation error "possible loss of precision".

byte b1 = (byte) s1;

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

View all for 65 types of Conversions

1 thought on “short to byte Java”

  1. byte has only 1 byte capacity to store data. but, here how was short data type type casted to byte. Isn’t possible 2 byte data implicit to 1byte data?

Leave a Comment

Your email address will not be published.