Character Literals Tutorial

Character literals can be represented in a couple of different ways. The standard representation for a character literal is a single character inside a pair of single quotes.

  • char a = 'A';
  • char one = '1';
If you haven't watched my tutorials on the Char Data Type and the Hexadecimal Literals, then the rest of this paragraph may not make much sense. The char data type is an unsigned 16-bit Unicode character. A character literal can be represented using Unicode notation. Unicode notation is the prefix of \u followed by four hexadecimal digits all enclosed in a pair of single quotes.
  • char A = '\u0041'; // decimal 65, ASCII letter A
  • char C = '\u0043'; // decimal 67, ASCII letter C
  • char T = '\U0054'; // decimal 84, ASCII letter T



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md CharacterLiterals
C:\Java>cd CharacterLiterals
C:\Java\CharacterLiterals>Notepad CharacterLiterals.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class CharacterLiterals {
    public static void main(String args[]) {
        char a = 'A';
        char one = '1';
        char A = '\u0041'; 
        char C = '\u0043';
        char T = '\u0054';

        System.out.println(a);
        System.out.println(one);
        System.out.print(C);
        System.out.print(A);
        System.out.print(T);                          

    }
}

Now switch back to the command prompt (CMD) and type in javac CharacterLiterals.java and press Enter.
Now type in java CharacterLiterals and press Enter.


C:\Java\CharacterLiterals>javac CharacterLiterals.java
C:\Java\CharacterLiterals>java CharacterLiterals
A
1
CAT


Tutorials