Java char type compare

Introduction

Two characters can be compared using the relational operators.

This is done by comparing the Unicode of the two characters.

For example,

  • 'a' < 'b' is true because the Unicode for 'a' (97) is less than the Unicode for 'b' (98).
  • 'a' < 'A' is false because the Unicode for 'a' (97) is greater than the Unicode for 'A' (65).
  • '1' < '8' is true because the Unicode for '1' (49) is less than the Unicode for '8' ( 56).

For example, the following code tests whether a character ch is an uppercase letter, a lowercase letter, or a digital character.

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

      if (ch >= 'A' && ch <= 'Z')
         System.out.println(ch + " is an uppercase letter");
      else if (ch >= 'a' && ch <= 'z')
         System.out.println(ch + " is a lowercase letter");
      else if (ch >= '0' && ch <= '9')
         System.out.println(ch + " is a numeric character");
   }/*from   ww  w .j  a va 2s  .c o  m*/
}



PreviousNext

Related