Using char value as integer

You can operate on char type variables as if they were integers. For example, consider the following program:


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

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

    ch1 = (char)(ch1 + 1); // 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. You have to cast ch1 + 1 back to char type since after adding 1 to ch1 the result becomes int type.

The output generated by this program is shown here:


ch1 contains X 
ch1 is now Y
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.