Java Reference
In-Depth Information
You can also assign an int literal to a char variable if int literal falls in the range 0-65535. When you assign an
int literal to a char variable, the char variable represents the character whose Unicode code is equal to the value
represented by that int literal. The Unicode code for the character 'a' (lowercase A) is 97. The decimal value 97 is
represented as 141 in octal and 61 in hexadecimal. You can represent the Unicode character 'a' in three different
forms in Java: 'a' , '\141' , and '\u0061' . You can also use int literal 97 to represent the Unicode character 'a' .
char c1 = 97; // Same as c1 = 'a'; c1 = '\141'; or, c1 = '\u0061';
A byte variable takes 8 bits and a char variable takes 16 bits. Even if the byte data type has smaller range than
the char data type, you cannot assign a value stored in a byte variable to a char variable. The reason is that byte is a
signed data type whereas char is an unsigned data type. If the byte variable has a negative value, say -15, it cannot be
stored in a char variable without losing the precision. In such a case, you need to use an explicit cast. The following
snippet of code illustrates possible cases of assignments from char to other integral data type and vice versa:
byte b1 = 10;
short s1 = 15;
int num1 = 150;
long num2 = 20L;
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
s1 = c1; // An error
s1 = (short)c1; // Ok
c1 = s1; // An error
c1 = (char)s1; // Ok
// 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 = 70000; // An error. 70000 is out of range 0-65535
c1 = (char)70000; // Ok. But, will lose the original value
// 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
Search WWH ::




Custom Search