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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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.
Enter Second String : Blog
First String is Greater than Second String.
That’s all about How to compare two Strings in java.
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.