In this post, we will see how to compare two String in java. Show
Output: Enter First String : JavaEnter Second String : Blog First String is Greater than Second String. That’s all about How to compare two Strings in java. Let us know if you liked the post. That’s the only way we can improve. In this article, you are going to learn how to compare strings and the problems that occur when you compare string using equals to (=)operator.
IntroductionThe String is a special class in Java. We use String regularly in Java programs, so comparing two strings is a common practice in Java. In this article, I tried to answer the most common questions about the string, like: "How do I compare strings in Java?" Comparing strings is very helpful during processes like authentication, sorting, reference matching, etc. I have listed three different ways to compare strings in Java.
1. Compare Strings Using the Equals() MethodIn this way, I am using .equals() instance method of the String class. Originally .equals() method is the Object class method, String class overrides it. equals() method compare two strings for value equality, whether they are logically equal. equals() method in String class takes another string as a parameter and compares it with the specified string. It returns true if — and only if — the parameter string is not null and contains the same characters as the specified string.
I have asked the program to compare strings using the equals() method below:
Output:
|