Syntax error Compare two objects of Character type in Java

Compare two objects of Character type in Java



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
Updated on: 2020-06-26T06:59:37+05:30

775 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements