Equals method in Java with example

Equals method in Java with example

In Java, there is a equals() method which is used to compare strings. This comparison of strings are based on the content of the string.

How the equals() method works in Java?

equals() methods compare two strings and if all characters of a string is not matched then it will return false. And If all the characters of the string matched it will return true.

equals() method of String class overrides the equals() method of Object class.

Below is the internal implementation of the equals() method.

[java]
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n– != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
[/java]

Signature and Parameter of equals() method

public boolean equals(Object anotherObject)

Return Type

boolean value true or false. if string is equal then return true otherwise return false.

Example 1: Java Program to check string are equal or not

[java]
public class Main{
public static void main(String args[]){
String s1=”tutorialworld”;
String s2=”tutorialworld”;
String s3=”java”;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
}
}
[java]
<!– /wp:shortcode –>

<!– wp:paragraph –>
<p><strong>Output:</strong></p>
<!– /wp:paragraph –>

<!– wp:image {“align”:”center”,”id”:900,”sizeSlug”:”full”,”linkDestination”:”none”} –>
<figure class=”wp-block-image aligncenter size-full”><img src=”https://tutorialworld.in/wp-content/uploads/2022/05/image-2.png” alt=”” class=”wp-image-900″/></figure>
<!– /wp:image –>

<!– wp:paragraph –>
<p>As you can see in the above example string s1 and s2 are the same as both have the same value <strong>”tutorialworld”</strong> but string s3 have different content “java”.</p>
<!– /wp:paragraph –>

<!– wp:paragraph –>
<p>So if we compare s1 and s2 then it returned true and if we have compared s1 and s3 then it has returned false as it is not equal.</p>
<!– /wp:paragraph –>

<!– wp:heading –>
<h2>Example 2: See Below one more example of List element comparision.</h2>
<!– /wp:heading –>

<!– wp:shortcode –>
[java]
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String str1 = “Prakash”;
ArrayList<String> name = new ArrayList<>();
name.add(“Ram”);
name.add(“Suresh”);
name.add(“Prakash”);
for (int i = 0; i < name.size(); i++){
if (name.get(i).equals(str1)) {
System.out.println(“Prakash is available in list”);
}
}
}
}
[/java]

Output: