For working professionals
For fresh graduates
More
The equals() function in Java is essential for detecting if two objects are equal. It is used to assess if two items are equal based on their content by comparing them. It is important to comprehend how this technique operates for appropriate object comparison and equality checking.
The java.lang.Object class contains the Java programming language's essential equals() function. All Java classes inherit it, and it may be changed to offer tailored equality comparisons for certain types. Equals() can be customized to compare the internal state of objects instead of just memory references, which is what it does by default.
Java's equals() function is used to determine whether two objects are equal. If the objects are equal, it returns true; if not, it returns false. This is the method signature:
javaCopy code
public boolean equals(Object obj)
The Object to be looked at is addressed by an Article, which is the contention for the equivalents() capability. The Object class in Java is the superclass of any remaining classes, which is a vital qualification to make. Subsequently, rises to() acknowledges any item as its feedback.
Example 1: Java String equals() Method
Let's start with a simple example using the equals() method with Java strings. In this example, we have two string objects, and we want to compare them for equality.
javaCopy code
String str1 = "Hello";
String str2 = "Hello";
boolean areEqual = str1.equals(str2);
System.out.println(areEqual); // Output: true
In the above code, we make two String objects, str1, and str2, with a similar substance. We then utilize the equivalents() technique to think about them. Since the two strings have a similar sense, the method returns valid, and it is equivalent to demonstrating that they.
Example 2: Java String equals() Method
In this example, we will demonstrate the case where two string objects have different content.
javaCopy code
String str1 = "Hello";
String str2 = "World";
boolean areEqual = str1.equals(str2);
System.out.println(areEqual); // Output: false
In the above code, str1 and str2 have different content, "Hello" and "World," respectively. When we compare them using the equals() method, it returns false since the content is not the same.
Example 3: Java String equals() Method
The equals() method is case-sensitive. It considers two strings with different cases as different.
javaCopy code
String str1 = "Hello";
String str2 = "hello";
boolean areEqual = str1.equals(str2);
System.out.println(areEqual); // Output: false
In the above code, str1 and str2 have the same characters but differ in case. As a result, the equals() method returns false.
Example 4: Java String equals() Method
The equals() method also works with null values. It returns false when comparing a non-null object with null.
javaCopy code
String str1 = "Hello";
String str2 = null;
boolean areEqual = str1.equals(str2);
System.out.println(areEqual); // Output: false
In the above code, we compare str1 with null. Since str2 is null, the equals() method returns false.
In Java, the == operator is used for reference equality testing. It compares the memory addresses of two objects to check if they are the same instance. Unlike the equals() method, the == operator does not consider the internal state or content of objects.
Example: "==" vs equals() Method
Let's compare the behavior of the == operator and the equals() method using an example.
javaCopy code
String str1 = "Hello";
String str2 = "Hello";
boolean usingOperator = str1 == str2;
boolean usingEqualsMethod = str1.equals(str2);
System.out.println(usingOperator); // Output: true
System.out.println(usingEqualsMethod); // Output: true
In the above code, both str1 and str2 reference the same string literal "Hello." The == operator returns true because it compares the memory addresses and finds that str1 and str2 point to the same object. Similarly, the equals() method compares the content of the strings, resulting in true.
The primary difference between the == operator and the equals() method lies in their behavior. The == operator compares the memory references of objects, while the equals() method compares their content.
Example: Comparing with "==" and equals() Method
Consider an example that highlights the difference between == and equals().
javaCopy code
String str1 = new String("Hello");
String str2 = new String("Hello");
boolean usingOperator = str1 == str2;
boolean usingEqualsMethod = str1.equals(str2);
System.out.println(usingOperator); // Output: false
System.out.println(usingEqualsMethod); // Output: true
Using the new keyword, we create two distinct String objects in the code above. Despite sharing the same content, the two objects are located at distinct memory locations. Because of contrasting the references, the == administrator gets back bogus. The equivalents() capability, then again, look at the substance of the strings and returns valid since the substance is indistinguishable.
When a class does not override the equals() method, it inherits the default implementation from the Object class. The default implementation compares object references, similar to the == operator.
Example: Using Default .equals() Method
Let's create a custom class that does not override the equals() method and observe its behavior.
javaCopy code
class Student {
private String name;
private int id;
public Student(String name, int id) {
this.name = name;
this.id = id;
}
}
Student student1 = new Student("John", 123);
Student student2 = new Student("John", 123);
boolean usingEqualsMethod = student1.equals(student2);
System.out.println(usingEqualsMethod); // Output: false
In the above code, we define a Student class without overriding the equals() method. When we compare two Student objects, student1, and student2, using the default equals() implementation, it returns false since the default behavior compares the object references.
To customize the equality comparison for a specific class, we can override the equals() method. By doing so, we can compare the internal state of objects instead of relying on the default reference comparison.
Example: Overriding equals() Method
Let's modify the Student class to override the equals() method and compare the internal state.
javaCopy code
class Student {
private String name;
private int id;
public Student(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Student student = (Student) obj;
return id == student.id && Objects.equals(name, student.name);
}
}
Student student1 = new Student("John", 123);
Student student2 = new Student("John", 123);
boolean usingEqualsMethod = student1.equals(student2);
System.out.println(usingEqualsMethod); // Output: true
In the modified code, we override the equals() method in the Student class. We compare the id and name fields of the objects for equality using the == operator and the Objects.equals() method, respectively. By overriding the equals() method, we can now compare the internal state of Student objects, resulting in true when the fields match.
The equality operator, ==, is used to compare primitive types and check if two references point to the same object. It does not perform content-based comparisons for non-primitive types.
Example: Equality Operator
Let's compare the behavior of the equality operator with primitive types and references.
javaCopy code
int num1 = 5;
int num2 = 5;
boolean usingOperator = num1 == num2;
System.out.println(usingOperator); // Output: true
String str1 = "Hello";
String str2 = "Hello";
boolean usingOperator = str1 == str2;
System.out.println(usingOperator); // Output: true
The == administrator is utilized in the code above to look at two int factors, num1, and num2. Since the worth of the two factors is 5, the administrator brings valid back. The administrator returns genuine when we analyze two string literals, str1, and str2, as the two of them allude to a similar string exacting in the string pool.
The equals() method is used to compare objects for equality based on their content. It can be overridden by classes to provide custom equality comparison logic.
Example: .equals() Method
Let's examine an example using the equals() method with custom objects.
javaCopy code
class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Book book = (Book) obj;
return Objects.equals(title, book.title) && Objects.equals(author, book.author);
}
}
Book book1 = new Book("Java Programming", "John Doe");
Book book2 = new Book("Java Programming", "John Doe");
boolean usingEqualsMethod = book1.equals(book2);
System.out.println(usingEqualsMethod); // Output: true
In the above code, we create a Book class that overrides the equals() method to compare the title and author fields of Book objects. The equals() method uses Objects. equals() to handle null-safe comparison. When we compare two Book objects, book1, and book2, using the equals() method, it returns true since the title and author fields match.
The equals() method in Java is crucial for comparing objects for equality based on their content. By default, it compares the memory references of objects, but it can be overridden to provide custom comparison logic. The == operator, on the other hand, compares the memory addresses of objects and is used for reference equality testing. For appropriate object comparison in Java, it is crucial to comprehend how the equals() method and the == operator vary from one another.
We looked at a variety of samples, pictures, and photographs to demonstrate how to use the equals() function and the == operator in this post. We learned how to utilize the default implementation offered by the Object class as well as how to customize the equals() function to compare the internal state of objects.
By mastering these concepts, developers can ensure accurate and meaningful equality comparisons in their Java programs.
Q1: Can we use the equals() method to compare arrays in Java?
A: The equals() function in Java does not, by default, offer array comparison. You can use Arrays.equals() or other utility methods to check whether two arrays are equal.
Q2: Can multiple types of objects be compared using the equals() method?
A: Yes, you may compare several object types using the equals() function. However, it must be handled properly and type-checked to prevent any mistakes.
Q3: What happens if we compare an object with null using the equals() method?
A: When comparing an object with null using the equals() method, it returns false. However, it is important to handle null checks to avoid NullPointerExceptions when using equals().
Q4: When should the equals() function in a custom class be overridden?
A: If you wish to check the internal states of objects for equality, it is advised to override the equals() function in a custom class. This is especially important when objects contain fields that determine their equality.
Take the Free Java Quiz & See Your Rank!
Pavan Vadapalli
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.