Compare two objects of Character type in Java

Java 8Object Oriented ProgrammingProgramming

To compare two objects of Character type in Java, use the compareTo() method.

Firstly, we have created two Character type.

Character one = new Character('m');
Character two = new Character('k');

Now, to compare them, we have used the compareTo() method.

int res = one.compareTo(two);

The following is the example that compares character objects.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      Character one = new Character('m');
      Character two = new Character('k');
      System.out.println("Character object 1: "+one);
      System.out.println("Character object 2: "+two);
      int res = one.compareTo(two);
      if (res == 0) {
         System.out.println("Both are equal!");
      } else if (res < 0) {
         System.out.println("Character 1 is less than Character 2");
      } else if (res > 0) {
         System.out.println("Character 1 is less than Character 2");
      }
   }
}

Output

Character object 1: m
Character object 2: k
Character 1 is less than Character 2
raja
Published on 10-Dec-2018 11:49:41
Advertisements