char to short Java

char to short Java

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.


char to short
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.

View all for 65 types of Conversions

Leave a Reply

Your email address will not be published. Required fields are marked *