Java Program to Check Whether two Strings are Equal or Not

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Java Program to Check Whether two Strings are Equal or Not

In this java program, to check whether two strings are equal or not we will use equals() method. This method compares this string with another string object and returns true only if both strings are equal else it returns false.

Java program to check whether two strings are equal or not

In this java program, we first ask user to enter two strings and store them in String objects “str1” and “str2”. Then we check whether str1 and str2 are equal or not by calling “equals” method.
Java program to check whether two strings are equal or not

package com.tcc.java.programs;
 
import java.util.Scanner;
 
public class StringEquality {
    public static void main(String args[]) {
        String str1, str2;
        Scanner scanner = new Scanner(System.in);
 
        System.out.println("Enter first String");
        str1 = scanner.nextLine();
 
        System.out.println("Enter second String");
        str2 = scanner.nextLine();
        // Comparing two input string
        if (str1.equals(str2))
            System.out.print("Equal Strings");
        else
            System.out.print("UnEqual Strings");
    }
}

Output

Enter first String
Apple
Enter second String
Apple
Equal Strings
Enter first String
Apple
Enter second String
Banana
UnEqual Strings