java tutorial - Java Strings compareTo() method - java programming - learn java - java basics - java for beginners



Description

  • Java Strings compareTo() method in Java is structured in two ways. First, the method compares the string with another object, and the second: the method compares two lines lexically.
  • How compareTo() works with a numeric object we covered in the last lesson. Consider the second option: comparing two lines.

Syntax

The syntax of the method is:

int compareTo(Object o)

or

int compareTo(String anotherString)
click below button to copy the code. By - java tutorial - team

Options

Detailed information about the parameters:

  • o - object to compare.
  • anotherString is a string for comparison.

Return value

  • In Java, compareTo() gets the value 0 if the argument is a string lexically equal to this string; the value is less than 0 if the argument is a lexically greater string than the string being compared; and the value is greater than 0 if the argument is a lexically lower string of this string.

Sample Code

public class Test {

   public static void main(String args[]) {
      String str1 = "Wikitechy is a good learner Website!";
      String str2 = "Wikitechy is a good learner Website!";
      String str3 = "I will be a good programmer!";

      int result = str1.compareTo(str2);
      System.out.println(result);
	  
      result = str2.compareTo(str3);
      System.out.println(result);
	 
      result = str3.compareTo(str1);
      System.out.println(result);
   }
}
click below button to copy the code. By - java tutorial - team

Output :

0
14
-14

Related Searches to Java Strings compareTo() method