How does the Java compareTo() method, compare strings?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Feb-2018 07:30:45
Advertisements