char

In Java, char stores characters.

Java uses Unicode to represent characters. Unicode can represent all of the characters found in all human languages.

Java char is a 16-bit type. The range of a char is 0 to 65,536.

There are no negative chars.

More information about Unicode can be found at http://www.unicode.org.

Here is a program that demonstrates char variables:


public class Main {
  public static void main(String args[]) {
    char ch1, ch2;

    ch1 = 88; // code for X

    ch2 = 'Y';

    System.out.print("ch1 and ch2: ");
    System.out.println(ch1 + " " + ch2);//ch1 and ch2: X Y
  }
}

ch1 is assigned the value 88, which is the ASCII (and Unicode) value that corresponds to the letter X.

char can be used as an integer type and you can perform arithmetic operations.


public class Main {
  public static void main(String args[]) {
    char ch1;

    ch1 = 'X';
    System.out.println("ch1 contains " + ch1);//ch1 contains X 

    ch1 = (char)(ch1 + 1); // increment ch1
    System.out.println("ch1 is now " + ch1);//ch1 is now Y
  }
}

char Literals

Characters in Java are indices into the Unicode character set. character is represented inside a pair of single quotes.

For example, 'a', 'z', and '@'.


public class Main {
  public static void main(String[] argv) {
    char ch = 'a';

    System.out.println("ch is " + ch);//ch is a

  }
}

public class Main {
  public static void main(String[] argv) {
    char ch = '@';

    System.out.println("ch is " + ch);//ch is @
    ch = '#';

    System.out.println("ch is " + ch);//ch is #
    ch = '$';

    System.out.println("ch is " + ch);//ch is $
    ch = '%';

    System.out.println("ch is " + ch);//ch is %

  }
}

The escape sequences are used to enter impossible-to-enter-directly characters.

'\'' is for the single-quote character.

'\n' for the newline character.

For octal notation, use the backslash followed by the three-digit number. For example, '\141' is the letter 'a'.

For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal digits. For example, '\u0061' is the ISO-Latin-1 'a' because the top byte is zero.

'\ua432' is a Japanese Katakana character.

The following table shows the character escape sequences.

Escape SequenceDescription
\dddOctal character (ddd)
\uxxxxHexadecimal Unicode character (xxxx)
\'Single quote
\"Double quote
\\Backslash
\rCarriage return
\nNew line
\fForm feed
\tTab
\bBackspace

public class Main {
  public static void main(String[] argv) {
    char ch = '\'';

    System.out.println("ch is " + ch);//ch is '

  }
}
Home 
  Java Book 
    Language Basics  

Primitive Types:
  1. The Primitive Types
  2. byte
  3. short
  4. int
  5. long
  6. float
  7. double
  8. char
  9. boolean