Java Fundamentals  «Prev 

Declare Char Literal in Java

The char data type stores individual characters of text such as A, E, I, etc.
Characters include text letters and symbols such as & and %, as well as special control characters that are not printable.
A string of text in Java can always be broken down into a series of characters. As an example, consider the string of text "JERRY".
This string of text consists of the five characters J, E, R, R, and Y. The relationship between characters and strings is significant because the number of characters in a string determines the string's length. Unlike C/C++, Java strings are not implemented as arrays of characters. Even though you can access characters within a string, Java strings use their own data type. More specifically, the String class is used to represent strings in Java. You will learn more about the String class a little later in the module.

Character Literals

A char literal is represented by a single character in single quotes:
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'

Characters are just 16-bit unsigned integers under the hood, which means you can assign a number literal, assuming it will fit into the unsigned 16-bit range (0 to 65535).
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;    // cast negative number, 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 (the backslash) if you want to represent a character that cannot be typed in as a literal, including the characters for linefeed, newline, horizontal tab, backspace, and quotes:
char c = '\"'; // A double quote
char d = '\n'; // A newline
char tab = '\t'; // A tab