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

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

This JAVA program is to compare two strings without using string method equals().

For example, str1=”code” and str2=”code” then on comparing we find that the two strings are equal.

Logic

We first check if both their lengths are equal. If strings are not equal, we need not go further with computation, thus increasing the efficiency of the program. If they are equal then we compare each string character by character.

Dry Run of the program

Take input s1 and s2.Let us take s1=code and s2=code

Convert s1 and s2 to char array str1 and str2 respectively

flag is set to 1 i.e. flag=1;

len1=s1.length() hence len1=4

len2=s2.length() hence len2=4

if(len1==len2)  i.e if(4==4) true

1st iteration for(i=0;i<len1;i++)   i .e.   for(i=0;0<4;i++)

if(str1[i]!=str2[i]) i.e if(str1[0]!=str2[0])  i.e if(c!=c) false

2nd iteration for(i=1;i<len1;i++)   i .e.   for(i=1;1<4;i++)

if(str1[i]!=str2[i]) i.e if(str1[1]!=str2[1])  i.e if(o!=o) false

3rd iteration for(i=2;i<len1;i++)   i .e.   for(i=2;2<4;i++)

if(str1[i]!=str2[i]) i.e if(str1[2]!=str2[2])  i.e if(d!=d) false

4th iteration for(i=3;i<len1;i++)   i .e.   for(i=3;3<4;i++)

if(str1[i]!=str2[i]) i.e if(str1[3]!=str2[3])  i.e if(e!=e) false

For loop ends here as i=4 which is not less than len1(4)

if(flag==1)  true

Hence the two strings are equal.

Program

import java.util.*;

class stringCompare
{
	public static void main(String args[])
	{
    		int i,flag=1,len1,len2;
		String s1,s2;
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the 1st string");
	 	s1=sc.nextLine();
		System.out.println("Enter the 2nd string");
	 	s2=sc.nextLine();

		len1=s1.length();
		len2=s2.length();

		char str1[] = s1.toCharArray();
		char str2[] = s2.toCharArray();

    	    	if(len1==len2)
    		{	
    			for(i=0;i<len1;i++)
    			{
        			if(str1[i]!=str2[i])
        			{
            				flag=0;
	                		break;
				}
        		}
		}
 	 	else
    		{
    			flag=0; 
   		}	
	    	if(flag==1)
    		{
 	        	System.out.println("The two string are EQUAL!!!");
        		System.out.println(s1+" = "+s2);
    		}

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

Output

Share Me!