Java char type

In this chapter you will learn:

  1. What is Java char type
  2. Size of Java char type
  3. Value range for Java char type
  4. Java char type literals
  5. Example - Java char type
  6. How to create char Literals
  7. Example - Store unicode into a char

Description

In Java, char stores characters. Java uses Unicode to represent characters. Unicode can represent all of the characters found in all human languages.

Size

Java char is a 16-bit type.

Value Range

The range of a char is 0 to 65,536. There are no negative chars.

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 '@'.

Example

Here is a program that demonstrates char variables:


public class Main {
  public static void main(String args[]) {
    char ch1, ch2;
//from  w  ww  . j  av  a  2  s.  c  o m
    ch1 = 88; // code for X

    ch2 = 'Y';

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

The code above generates the following result.

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

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


public class Main {
  public static void main(String args[]) {
    char ch1;/*from w  w  w.  j a v a2s.  c  o  m*/

    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
  }
}

Example 2


public class Main {
  public static void main(String[] argv) {
    char ch = 'a';
/*from   w w  w .  j a va 2  s.  c om*/
    System.out.println("ch is " + ch);//ch is a
    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 code above generates the following result.

Example 3

The following code stores unicode value into a char variable. The unicode literal uses \uxxxx format.


public class Main {
  public static void main(String[] args) {
    int x = 75;//from   w  ww.  j av a  2s. c  om
    char y = (char) x;
    char half = '\u00AB';
    System.out.println("y is " + y + " and half is " + half);

  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Why to escape char value
  2. Syntax to escape char value
  3. Example - char escape value
  4. List of Escape value
Home »
  Java Tutorial »
    Java Langauge »
      Java Data Types
Java Primitive Data Types
Java boolean type
Java char type
Java char value escape
Java byte type
Java short type
Java int type
Java long type
Java float type
Java double type
Java String type
Java String Escape
Java String Concatenation