Java Program to Check Whether two Strings are Equal or Not

Here is a 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.

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

Recommended Posts
Java Program to Check Two Strings are Anagram or Not
Java Program to Reverse a String
Java Program to Find Length of a String
Java Program to Concatenate Two Strings
Java Program to Copy a String
Java Program to Delete All Spaces from a String
Java Program to Find Count of Each Character in a String
Java Program to Delete all Vowel Characters from String
Java Program to Count Words in a Sentence
Java Program to Delete a Word from Sentence
Java Program to Reverse Sequence of Words of a Sentence
All Java Programs