After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast char to short.
The short takes 2 bytes of memory and char takes 2 bytes of memory. Here, casting rules do not work as short can take a negative value where as char is always positive. The type conversion from char to short requires explicit casting. It should be noted that any data type conversion to char requires explicit casting (explicit type conversion takes care of negative value). Explicit casting truncates the mantissa (value after decimal point) part of float and double. "boolean" is also incompatible to convert into char.
Either char to short or short to char requires explicit casting.
Following program on char to short explains the Java syntax of explicit casting.
public class Conversions
public static void main(String args)
char ch = 'A'; // 2 bytes
// short s1 = ch; // error, char to short
short s1 = (short) ch; // explicit conversion from char to short
System.out.println("char value: " + ch); // prints A
System.out.println("Converted short value: " + s1); // prints 65 (ASCII value of A)
Output screenshot of char to short Java
short s1 = ch;
The above statement raises a compilation error "possible loss of precision".
short s1 = (short) ch;
The char ch is explicitly type casted to short s1. Observe the syntax of explicit casting. On both sides, it should be short only.