In this article we will show you the solution of how to compare strings in java, utilising Java's equals() method, we can compare strings. The String class provides this function.
The equals() method compares the contents of two strings and returns true if they are equal or false otherwise.
Set up the two string variables we want to compare and declare them. Use the equals() method to compare the strings.
Pass the second string as a parameter when using the equals() function on one string.
Based on the outcome of the comparison, the equals() method returns a value of type Boolean (true or false). This value can be kept in a Boolean variable and used later.
The Boolean variable can now be used to execute conditional operations or print the outcome.
Step By Step Guide On How To Compare Strings In Java :-
package A; public class CompareString { public static void main(String[] args) { String input1 = "IsEqual"; String input2 = "NotEqual"; String input3 = "IsEqual"; boolean Equal = input1.equals(input3); if (Equal) { System.out.println("The strings are equal."); } else { System.out.println("The strings are not equal."); } } }
- The programme is located in a package called A. Simply put, this is how Java classes are organised.
- There is a declaration for the CompareString class, which includes the main method.
- "IsEqual" is assigned to input1.
- "NotEqual" is assigned to input2.
- "IsEqual" is assigned to input3.
- The input1 and input3 are compared using the equals() technique. The boolean variable holds the comparison's outcome.
- The value of Equal is verified using an if statement. If it is true, it indicates that the strings are equal and prints "The strings are equal." Otherwise, the message stating "The strings are not equal." is printed if it is false.
Conclusion :-
In conclusion, invoking the equals() method to compare strings in Java is a simple procedure.
When two strings are compared using the equals() method, it determines whether their contents are equal and returns true otherwise.
I hope this article on how to compare strings in java helps you and the steps and method mentioned above are easy to follow and implement.