Java – String compareTo() Method example

by Chaitanya Singh

in String handling

The method compareTo() is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns positive or negative value. The result is positive if the first string is lexicographically greater than the second string else the result would be negative.

This method can be used as follows:

int compareTo(String str)

Here the comparison is between string literals. For e.g. string1.compareTo(string2) where string1 and string2 are String literals.

int compareTo(Object obj)

This is a comparison between a string and an object. For e.g. string1.compareTo("Just a String object") where string1 is a literal whose value would be compared with the string specified in the method argument.

Example

Here we have three Strings and we are comparing them with each other using compareTo() method.

public class CompareToExample {
   public static void main(String args[]) {
       String str1 = "String method tutorial";
       String str2 = "compareTo method example";
       String str3 = "String method tutorial";

       int var1 = str1.compareTo( str2 );
       System.out.println("str1 & str2 comparison: "+var1);

       int var2 = str1.compareTo( str3 );
       System.out.println("str1 & str3 comparison: "+var2);

       int var3 = str2.compareTo("compareTo method example");
       System.out.println("str2 & string argument comparison: "+var3);
   }
}

Output:

str1 & str2 comparison: -16
str1 & str3 comparison: 0
str2 & string argument comparison: 0

{ 0 comments… add one now }

Leave a Comment

Our Friend's website link : FromDev.com