Java Reference ยท Types and Literals
The char type
Reference for Java char: a 16-bit unsigned UTF-16 code unit, character literals and escapes, arithmetic on chars, Character helpers and code points.
char is a 16-bit unsigned integer that represents one UTF-16 code unit. Values range from 0 to 65,535 ('\u0000' to '๏ฟฟ'). A char literal is written in single quotes: 'A', '7', '\n', 'รฉ'.
Because char is numeric, you can compare it, add to it and use it in a switch. But a char is not always a whole character: symbols outside the Basic Multilingual Plane, such as most emoji, need two chars (a surrogate pair). For those, work with code points.
char letter = 'A'; char next = (char) (letter + 1); // 'B'
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
char c = 'x'; char c = 'A'; // Unicode escape char c = 65; // int constant that fits in 0..65535
| Property | Value |
|---|---|
| Size | 16 bits, unsigned |
| Range | '\u0000' (0) to '๏ฟฟ' (65,535) |
| Default value | '\u0000' |
| Wrapper class | java.lang.Character |
Common escapes: \n, \t, \r, \b, \f, \s (space), \', \", \\, octal \0 to \377, and \uXXXX.
Usage notes
- Arithmetic yields
int.c + 1is an int; cast back tochar, or usec++andc += 1, which keep the type. - Single versus double quotes.
'a'is achar;"a"is aString.'ab'does not compile. - Adding chars to a string.
"" + 'a' + 'b'is"ab", but'a' + 'b' + ""is"195", because the two chars are added numerically first. - Not always a full character.
String.length()andcharAt()count UTF-16 code units. UsecodePoints(),codePointAt()andCharacter.charCount()for text that may include emoji or rare scripts. - Use the
Charactermethods (isLetter,isDigit,toUpperCase) instead of range tests likec >= 'a' && c <= 'z'; they handle all of Unicode. Theintoverloads accept code points. - Unicode escapes are processed early.
\u000ainside source code is turned into a real newline by the compiler before parsing, which can break a comment or literal. Prefer\n. charis unsigned, so(char) -1is65535.