Java.lang.String.compareTo() Method

Java.lang.String.compareTo() Method

Advertisements

Description

The java.lang.String.compareTo() 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.

  • The result is a negative integer if this String object lexicographically precedes the argument string.
  • The result is a positive integer if this String object lexicographically follows the argument string.
  • The result is zero if the strings are equal, compareTo returns 0 exactly when the equals(Object) method would return true.

Declaration

Following is the declaration for java.lang.String.compareTo() method

public int compareTo(String anotherString)

Parameters

anotherString − This is the String to be compared.

Return Value

This method returns the value 0 if the argument string is equal to this string, a value less than 0 if this string is lexicographically less than the string argument and a value greater than 0 if this string is lexicographically greater than the string argument.

Exception

NA

Example

The following example shows the usage of java.lang.String.compareTo() method.

package com.tutorialspoint;

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");
      }
   }
}

Let us compile and run the above program, this will produce the following result −

str1 is greater than str2

java_lang_string.htm

Advertisements