JAVA program to compare two strings using string method equals()

JAVA program to compare two strings using string method equals()

This JAVA program is to compare two strings using string method equals(String). String method equals() compares the two strings.

Return boolean values str1.equals(str2)

  • True if both strings have same content.
  • False if both strings have different content

Note :- When we compare strings in java do not use “==” operator as it compares the reference to the objects and not the content of the strings.

Logic

We just compare the two strings. This Java method str1.equals(str2) will compare string str1 with string str2.

Any other further queries, you can leave it in the comment box.

Program

import java.util.*;

class stringCompareF
{
	public static void main(String args[])
	{
		String str1,str2;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the 1st string");
	 	str1=sc.nextLine();
		System.out.println("Enter the 2nd string");
	 	str2=sc.nextLine();
		
		if(str1.equals(str2))
    		{
 	        	System.out.println("The two string are EQUAL!!!");
        		System.out.println(str1+" = "+str2+"("+(str1.equals(str2))+")");
    		}

    		else
    		{
 	        	System.out.println("The two string are NOT EQUAL!!!");
        		System.out.println(str1+" != "+str2+"("+(str1.equals(str2))+")");
    		}
	}
}

Output

Share Me!