Java.lang.Character.compareTo() Method



The java.lang.Character.compareTo(Character anotherCharacter) compares two Character objects numerically.


Following is the declaration for java.lang.Character.compareTo() method

public int compareTo(Character anotherCharacter)

Specified by

compareTo in interface Comparable<Character>


anotherCharacter − the Character to be compared

Return Value

This method returns the value 0 if the argument Character is equal to this Character, a value less than 0 if this Character is numerically less than the Character argument; and a value greater than 0 if this Character is numerically greater than the Character argument (unsigned comparison). This is strictly a numerical comparison; it is not locale-dependent.




The following example shows the usage of lang.Character.compareTo() method.

package com.tutorialspoint;

import java.lang.*;

public class CharacterDemo {

   public static void main(String[] args) {

      // create 2 Character objects c1, c2
      Character c1, c2;

      // assign values to c1, c2
      c1 = new Character('a');
      c2 = new Character('b');

      // create an int type
      int res;

      // compare c1 with c2 and assign result to res
      res = c1.compareTo(c2);

      String str1 = "Both values are equal ";
      String str2 = "First character is numerically greater";
      String str3 = "Second character is numerically greater";

      if( res == 0 ) {
         System.out.println( str1 );
      } else if( res > 0 ) {
         System.out.println( str2 );
      } else if( res < 0 ) {
         System.out.println( str3 );

Let us compile and run the above program, this will produce the following result −

Second character is numerically greater