Java compareTo Method to Compare Strings



The compareTo() method compares the Number object that invoked the method to the argument. It is possible to compare Byte, Long, Integer, etc.

However, two different types cannot be compared, both the argument and the Number object invoking the method should be of the same type.

Example

Live Demo

public class Test {
   public static void main(String args[]) {
      Integer x = 5;
      System.out.println(x.compareTo(3));
      System.out.println(x.compareTo(5));
      System.out.println(x.compareTo(8));
   }
}

Output

1
0
-1
Updated on: 2020-02-26T09:41:58+05:30

133 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements