Many methods exist in java.lang.Character class used for different purposes. Some methods are useful for checking the character is a digit or letter or is a uppercase letter or lowercase letter etc. At the sametime, some methods can modify the case of the letters from uppercase to lowercase or vice versa.
Now the present method compareTo() is useful to compare two character objects. This method uses internally compareTo() method of interface Comparable. This is possible as Character class implements Comparable interface.
Following is the method signature as defined in java.lang.Character class.
- public int compareTo(Character c1): Compares two Character objects numerically. Returns an integer value of their ASCII value difference.
Following example on Java Character compareTo() Example illustrates.
public class CharacterFunctionDemo
public static void main(String args)
Character c1 = new Character('A'); // ASCII value 65
Character c2 = new Character('C'); // ASCII value 67
System.out.println("compareTo() with characters A and A: " + c1.compareTo(c1)); // 65-65
System.out.println("compareTo() with characters A and C: " + c1.compareTo(c2)); // 65-67
System.out.println("compareTo() with characters C and A: " + c2.compareTo(c1)); // 67-65
Output screenshot on Java Character compareTo() Example