Java - char type to integral data type cast

byte and char

You cannot assign a value stored in a byte variable to a char variable since byte is a signed data type whereas char is an unsigned data type.

byte b1 = 10; 
char c1 = 'A'; 

// byte and char 
b1 = c1;        // An error 
b1 = (byte)c1;  // Ok 
c1 = b1;        // An error 
c1 = (char)b1;  // Ok 

short and char

short s1 = 15; 
char c1 = 'A'; 

// short and char 
s1 = c1;         // An error 
s1 = (short)c1;  // Ok 
c1 = s1;         // An error 
c1 = (char)s1;   // Ok 
  

int and char

int num1 = 150; 
char c1 = 'A'; 

// int and char 
num1 = c1;        // Ok 
num1 = (int)c1;   // Ok. But, cast is not required. Use num1 = c1 
c1 = num1;        // An error 
c1 = (char)num1;  // Ok 
c1 = 255;         // Ok. 255 is in the range of 0-65535 
c1 = 90000;       // An error. 90000 is out of range 0-65535 
c1 = (char)90000; // Ok. But, will lose the original value 

long and char

char c1 = 'A'; 
long num2 = 20L; 
// long and char 
num2 = c1;        // Ok 
num2 = (long)c1;  // Ok. But, cast is not required. Use num2 = c1 
c1 = num2;        // An error 
c1 = (char)num2;  // Ok 
c1 = 255L;        // An error. 255L is a long literal 
c1 = (char)255L;  // Ok. But use c1 = 255 instead 

Related Topics