Java Programming - Language Fundamentals - Discussion
- char c1 = 064770;
- char c2 = 'face';
- char c3 = 0xbeef;
- char c4 = \u0022;
- char c5 = '\iface';
- char c6 = '\uface';
(1), (3), and (6) are correct. char c1 = 064770; is an octal representation of the integer value 27128, which is legal because it fits into an unsigned 16-bit integer. char c3 = 0xbeef; is a hexadecimal representation of the integer value 48879, which fits into an unsigned 16-bit integer. char c6 = '\uface'; is a Unicode representation of a character.
char c2 = 'face'; is wrong because you can't put more than one character in a char literal. The only other acceptable char literal that can go between single quotes is a Unicode value, and Unicode literals must always start with a '\u'.
char c4 = \u0022; is wrong because the single quotes are missing.
char c5 = '\iface'; is wrong because it appears to be a Unicode representation (notice the backslash), but starts with '\i' rather than '\u'.
So, 1 is not valid.
char c5 = '\iface'; //illegal
char c6 = '\uface'; //legal
char a = 'a';
char b = '@';
You can also type in the Unicode value of the character, using the Unicode.
Notation of prefixing the value with \u as follows:
char letterN = '\u004E'; // The letter 'N'.
Remember, characters are just 16-bit unsigned integers under the hood. That means you can assign a number literal, assuming it will fit into the unsigned 16-bit range (65535 or less). For example, the following are all legal:
char a = 0x892; // hexadecimal literal.
char b = 982; // int literal.
char c = (char) 70000; // The cast is required; 70000 is out of char range.
char d = (char) -98; // Ridiculous, but legal.
And the following are not legal and produce compiler errors:
char e = -29; // Possible loss of precision; needs a cast.
char f = 70000 // Possible loss of precision; needs a cast.
You can also use an escape code if you want to represent a character that can't be. Typed in as a literal, including the characters for linefeed, newline, horizontal tab, Backspace, and single quotes.
char c = '\"'; // A double quote.
char d = '\n'; // A newline.