byte to char Java

byte to char Java

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

The byte takes 1 byte of memory and char takes 2 bytes of memory. Here, casting rules do not work like 1 byte value can be assigned to 2 bytes implicitly, as byte can take negative values where as char does not. The explicit conversion takes care of this.

Either byte to char or char to byte requires explicit casting.

Following program example on byte to char explains the explicit casting procedure. Observe, the Java syntax of doing so.


byte to char
Output screenshot of byte to char Java

char ch = b1;

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

char ch = (char) b1;

The byte b1 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

One thought on “byte to char Java

Leave a Reply

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