Character in Java

If you are dealing with a single character value, you can store it in char variable. A single character value is a character inside two quotes. Here is an example:

char mykey = 'a';

A char variable can accept ASCII and UNICODE character. The example above was the ascii character which their numeric value is a number between 0 two 255.

Save following content in a .java file called TryChar.java. Note that the file name is equivalent to your class name TryChar.

public class TryChar {
  public static void main(String[] args) {
     char tryChar1 = 'A';
     System.out.print("tryChar1 char value: ");
     System.out.println(tryChar1);
     System.out.print("tryChar1 ascii code: ");
     System.out.println((int) tryChar1);

     char tryChar2 = 'ß';
     System.out.print("tryChar2 value: ");
     System.out.println(tryChar2);
     System.out.print("tryChar2 ascii code: ");
     System.out.println((int) tryChar2);

     char tryChar3 = 124;
     System.out.print("tryChar3 value: ");
     System.out.println(tryChar3);
     System.out.print("tryChar3 ascii code: ");
     System.out.println((int) tryChar3);

     char tryChar4 = '\u2142';
     System.out.print("tryChar4 value: ");
     System.out.println(tryChar4);
     System.out.print("tryChar4 Unicode code: ");
     System.out.println((int) tryChar4);
  }
}

Using javac command compile your .java file

$ javac TryChar.java

And using java command run it.

$ java TryChar
 tryChar1 char value: A
 tryChar1 ascii code: 65
 tryChar2 value: ß
 tryChar2 ascii code: 223
 tryChar3 value: |
 tryChar3 ascii code: 124
 tryChar4 value: ⅂
 tryChar4 Unicode code: 8514

In Java, a char variable is technically a two bytes (16 bits) variable type that you can assign a single unicode character via the character symbol inside two quotes like this:

 char tryChar2 = 'ß';

or assign a number value like this that represent pipe | character:

char tryChar3 = 124;

or you can assign a unicode character:

char tryChar4 = '\u2142';

That represents this character symbol with a decimal value of 8514