String’s compareTo method compares two String lexicographically. Both String get converted to unicode value and then compares.
When you run above program, you will get below output:
If you call str1.compareTo(str2)
then if it returns
positive number : str1 is greater than str2
0: str1 is equal to str2
negative number : str1 is smaller than str2
Java String compareTo example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package org.arpit.java2blog; public class StringCompareToExampleMain { public static void main(String[] args) { String str1="java2blog"; String str2="hello"; String str3="world"; String str4="java2blog"; String str5="JAVA2BLOG"; System.out.println("comparing java2blog with hello : "+str1.compareTo(str2)); System.out.println("comparing hello with world : "+str2.compareTo(str3)); System.out.println("comparing java2blog with java2blog : "+str1.compareTo(str4)); System.out.println("comparing java2blog with JAVA2BLOG : "+str1.compareTo(str5)); } } |
1 2 3 4 5 6 |
comparing java2blog with hello : 2 comparing hello with world : -15 comparing java2blog with java2blog : 0 comparing java2blog with JAVA2BLOG : 32 |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.