Home >>Java String Methods >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.
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; }
public boolean equals(Object anotherObject)
anotherObject - Another object, that is, compared to the string.
True if all string characters are otherwise equally false.
Method java Object type equals()
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));
}
}
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");
}
}
}
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");
}
}
}
}