char to byte Java

char to byte Java

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

The byte takes 1 byte of memory and char takes 2 bytes of memory. Here, casting rules do not work as byte can take a negative value where as char is always positive (char is unsigned by default in every language). The type conversion from char to byte 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 incompatible to convert into char.

Either char to byte or byte to char requires explicit casting. Following program explains.


char to byte
Output screenshot of char to byte Java

byte b1 = ch;

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

byte b1 = (byte) ch;

The char ch is explicitly type casted to byte b1. Observe the syntax of explicit casting. On both sides, it should be byte only. It is known as narrowing conversion.

Leave a Reply

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