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.
public class Conversions
public static void main(String args)
char ch = 'A'; // 2 bytes
// byte b1 = ch; // error, 2 bytes to 1 byte
byte b1 = (byte) ch; // explicit conversion from char to byte
System.out.println("char value: " + ch); // prints A
System.out.println("Converted byte value: " + b1); // prints 65 (ASCII value A)
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.