Home >>Java String Methods >Java String equals() method

Java String equals() method

Java String equals() method

The equals() method in java string is used to compares the two strings given, based on the string content. If any characters are not matched, then it will return false. If all characters match, then this returns true.

Internal implementation

public boolean equals(Object anObject) {  
      if (this == anObject) {  
          return true;  
      }  
      if (anObject instanceof String) {  
          String anotherString = (String) anObject;  
          int x = value.length;  
          if (x == anotherString.value.length) {  
              char n1[] = value;  
              char n2[] = anotherString.value;  
              int i = 0;  
              while (x-- != 0) {  
                  if (n1[i] != n2[i])  
                          return false;  
                  i++;  
              }  
              return true;  
          }  
      }  
      return false;  
  }  

Signature

public boolean equals(Object anotherObject)

Parameter

anotherObject - Another object, that is, compared to the string.

Returns

True if all string characters are otherwise equally false.

Overrides

Method java Object type equals()

String equals() method example 1

public class EqualsExample
{  
public static void main(String args[])
{  
String n1="phptpoint";  
String n2="PHPTPOINT";  
String n3="phptpoint";  
String n4="Java";  
System.out.println(n1.equals(n2)); 
System.out.println(n1.equals(n3));  
System.out.println(n1.equals(n4)); 
}
}  

Output
false
true
false
String equals() Method Example 2

public class EqualsExample 
{  
    public static void main(String[] args) 
	{  
        String nm1 = "phptpoint";    
        String nm2 = " phptpoint ";    
        String nm3 = "Phptpoint";  
        System.out.println(nm1.equals(nm2)); 
        if (nm1.equals(nm3)) 
		{  
            System.out.println("both are equal");  
        }
		else
		{
		System.out.println("both are unequal");
		}	
    }  
}  

Output
True
both are unequal
String equals() Method Example 3

Let's see another example to check the string equality present in the list.


import java.util.ArrayList;  
public class EqualsExample3 
{  
    public static void main(String[] args) 
	{  
        String name = "One";  
        ArrayList<String> list = new ArrayList<>();  
        list.add("One");   
        list.add("Two");  
        list.add("Three");  
        list.add("Four");  
        for (String str : list) 
		{  
            if (str.equals(name)) 
			{  
                System.out.println("One is the first number");  
            }  
        }  
    }  
}  

Output
One is the first number

No Sidebar ads