Java String compareTo example

String’s compareTo method compares two String lexicographically. Both String get converted to unicode value and then compares.

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

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

}

When you run above program, you will get below output:

comparing java2blog with hello : 2
comparing hello with world : -15
comparing java2blog with java2blog : 0
comparing java2blog with JAVA2BLOG : 32
[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.