Java char type

Introduction

Java stores characters via char type.

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.

The standard set of characters known as ASCII ranges from 0 to 127.

Here is a program that demonstrates char variables:

// Demonstrate char data type.
public class Main {
  public static void main(String args[]) {
    char ch1, ch2;

    ch1 = 88;  // code for X
    ch2 = 'Y';// ww  w  .j av a2  s. c o  m
    
    System.out.print("ch1 and ch2: ");
    System.out.println(ch1 + " " + ch2);
  }
}

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

Although char is designed to hold Unicode characters, it can also be used as an integer type.

We can perform arithmetic operations on char type.

For example, you can add two characters together, or increment the value of a character variable.

The following code uses char variables behave like integers.

// char variables behave like integers. 
public class Main {
  public static void main(String args[]) {
    char ch1;/*www  .  j  a va2 s .co m*/

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

    ch1++; // increment ch1
    System.out.println("ch1 is now " + ch1);
  }
}

In the program, ch1 is first given the value X.

Then, ch1 is incremented.

This results in ch1 containing Y, the next character in the ASCII and Unicode sequence.




PreviousNext

Related