short to char Java


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

The char and short, each takes 2 byte of memory. Assignment of short to char requires explicit casting as short can take negative values also but char does not.

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

short to char is a typical conversion where short and char takes equal size memory of 2 bytes each. Here, casting rules do not apply like lower size value to higher size value implicitly.

Examples of implicit casting

short x = 10;
int y = x;

byte x = 10;
short y = x;

Following program on short to char explains explicit casting. Observe, the Java syntax where short value assigned to a char.

public class Conversions
{
  public static void main(String args[])
  {
    short s1 = 65;
    // char ch = s1;  

    char ch = (char) s1;  

    System.out.println("short value: " + s1);   // prints 65
    System.out.println("Converted char vale: " + ch);   // prints A (65 is the ASCII value of A)   
  }
}


short to char
Output screenshot of short to char Java

char ch = s1;

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

char ch = (char) s1;

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

View all for 65 types of Conversions

Leave a Comment

Your email address will not be published.