01.What is the "equals() Methods"?
The equals() method is defined in the Object class (the parent class of all Java classes).
It is used to compare two objects for equality.
Advatage:
1.Allows content comparison of objects
2.Can be overridden for custom logic
3.Makes code usability
4.Works well with HashSet, HashMap
DisAdvantages:
1.Default compares only references
2.Wrong implementation breaks collections
3.Can be slower for deep object comparisons
4.Requires careful coding with hashCode()
02.What are the Equals() methods?
1. String -Equal() Method:
The argument value is equal is known as the string equal method.
Because they are compare the two arugument value so output is true.
Example:
String v1 = "Hi";
String v2 = "Hi";
System.out.println(v1.equals(v2));
System.out.println(v1.hashCode());
System.out.println(v2.hashCode());
2. StringBuffer-Equal Method:
If the argument value is same but the output is false because StringBuffer equal method is compare the HashCode.
Hashcode is a memory address.
Example:
StringBuffer b1 = new StringBuffer("Hi");
StringBuffer b2 = new StringBuffer("Hi");
System.out.println(b1.equals(b2));
System.out.println(b1.hashCode());
System.out.println(b2.hashCode());
3. StringBuilder-Equal Method:
If the argument value is same but the output is false because StringBuilder equal method is compare the HashCode.
Hashcode is a memory address.
Example:
StringBuilder w1 = new StringBuilder("Hello");
StringBuilder w2 = new StringBuilder("Hello");
System.out.println(w1.equals(w2));
System.out.println(w1.hashCode());
System.out.println(w2.hashCode());
03.What is the HashCode?
The hashCode() method is defined in the Object class.
It returns an integer value (hash code) that represents the object in memory.
Relationship with equals():
If two objects are equal (equals() == true) → they must have the same hashCode().
If two objects have the same hashCode(), they may or may not be equal
Advatage:
1.Improves Performance
2.Efficient Memory Usage
3.Works with equals() to prevent duplicates
DisAdvantages:
1.Not Unique
2.Platform Dependency
3.Incorrect overriding causes bugs
04. What is the double Equal method?
The double equal (==) operator checks value for primitives and reference (memory address) for objects, while equals() is used to check content equality for object
The argument value is equal is known as the string equal method.
Because they are compare the two arugument value so output is true.
Example:
int no1 = 10;
int no2 = 10;
System.out.println(no1 == no2);
Advantages:
1.Simple and Fast
2.Clear for Primitives
3.Reference Comparison for Objects
4.No Method Call Overhead
DisAdvantages:
1.Not Suitable for Object Content
2.Cannot Be Overridden
3.Limited Usefulness
Top comments (0)