How does the Java compareTo() method, 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: 26-Feb-2020

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements