JVM Knowledge

A character literal is expressed as a character or an escape sequence (§3.10.7), enclosed in ASCII single quotes. (The single-quote, or apostrophe, character is \u0027.)

CharacterLiteral:
  ' SingleCharacter '
  ' EscapeSequence '

SingleCharacter:
  InputCharacter but not ' or \

A character literal is always of type char (§4.2.1).

The content of a character literal is the SingleCharacter or the EscapeSequence which follows the opening '.

It is a compile-time error for the character following the content to be other than a '.

It is a compile-time error for a line terminator (§3.4) to appear after the opening ' and before the closing '.

The characters CR and LF are never an InputCharacter; each is recognized as constituting a LineTerminator, so may not appear in a character literal, even in the escape sequence \ LineTerminator.

The character represented by a character literal is the content of the character literal with any escape sequence interpreted, as if by execution of String.translateEscapes on the content.

Character literals can only represent UTF-16 code units (§3.1), i.e., they are limited to values from \u0000 to \uffff. It is a compile-time error to attempt to represent a supplementary character in a character literal. Supplementary characters must be represented either as a surrogate pair within a char sequence, or as an integer, depending on the API they are used with.

The following are examples of char literals:

  • 'a'
  • '%'
  • '\t'
  • '\\'
  • '\''
  • '\u03a9'
  • '\uFFFF'
  • '\177'
  • '™'

Because Unicode escapes are processed very early, it is not correct to write '\u000a' for a character literal whose value is linefeed (LF); the Unicode escape \u000a is transformed into an actual linefeed in translation step 1 (§3.3) and the linefeed becomes a LineTerminator in step 2 (§3.4), so the character literal is not valid in step 3. Instead, one should use the escape sequence '\n'. Similarly, it is not correct to write '\u000d' for a character literal whose value is carriage return (CR). Instead, use '\r'. Finally, it is not possible to write '\u0027' for a character literal containing an apostrophe (').

In C and C++, a character literal may contain representations of more than one character, but the value of such a character literal is implementation-defined. In the Java programming language, a character literal always represents exactly one character.