How to Compare Two Strings in Java

In this post, we will see how to compare two String in java.
As you might know, String implements Comparable interface, you can use compareTo method to compare two String in java.

import java.util.Scanner;

public class StringComparator
{
   public static void main(String args[])
   {
      String str1, str2;
      Scanner scan = new Scanner(System.in);

      System.out.print("Enter First String : ");
      str1 = scan.nextLine();

      System.out.print("Enter Second String : ");
      str2 = scan.nextLine();

      if(str1.compareTo(str2) > 0){
         System.out.println("First String is Greater than Second String.");
      }else if(str1.compareTo(str2) < 0){
         System.out.println("First String is Smaller than Second String.");
      }else{
         System.out.println("Both Strings are Equal (i.e. String1 is Equal to String2)");
      }
   }
}

Output:

Enter First String : Java
Enter Second String : Blog
First String is Greater than Second String.

That’s all about How to compare two Strings in java.

[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.