Compare the two Strings lexicographically in Java

Java Programming Java8Object Oriented ProgrammingJava RMIJsoup

The compareTo() method of the String class. This method compares two Strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. This method returns

  • a negative integer if current String object lexicographically precedes the argument string.
  • a positive integer if current String object lexicographically follows the argument.
  • true when the strings are equal.

Example

import java.lang.*;
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "tutorials", str2 = "point";
      // comparing str1 and str2
      int retval = str1.compareTo(str2);
      // prints the return value of the comparison
      if (retval < 0) {
         System.out.println("str1 is greater than str2");
      } else if (retval == 0) {
         System.out.println("str1 is equal to str2");
      } else {
         System.out.println("str1 is less than str2");
      }
   }
}

Output

str1 is less than str2
raja
Published on 26-Jul-2018 10:50:43
Advertisements