All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

How To Compare Strings In Java

Last Updated : Mar 11, 2024

How To Compare Strings In Java

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.");
        }
    }
}
  1. The programme is located in a package called A. Simply put, this is how Java classes are organised.
  2. There is a declaration for the CompareString class, which includes the main method.
  3. "IsEqual" is assigned to input1.
  4. "NotEqual" is assigned to input2.
  5. "IsEqual" is assigned to input3.
  6. The input1 and input3 are compared using the equals() technique. The boolean variable holds the comparison's outcome.
  7. 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.

Author Image About Amruta

Amruta is an Experienced web developer with 4 years for experience she completed her master's with MCA and passionate about programming Languages for creating technical contents like HTML, CSS, JavaScript, Java, Python, PHP, jQuery.

Follow Amruta On Linkedin 🡪