Understanding == vs .equals() in Java: A Comprehensive Guide
Naveen Reddy
Software Engineer-Capgemini | Upskilling in DSA, MySQL, Java, Low & High-Level Design At Scaler Academy
In Java, comparing objects might seem straightforward, but it often leads to confusion due to the different methods available. Two of the most common methods for comparison are == and .equals(). Understanding the difference between these two can help you avoid bugs and write more effective Java code.
The == Operator
The == operator is used for reference comparison, meaning it checks whether two references point to the same object in memory. It does not compare the contents of the objects, only their memory addresses.
Examples:
String s1 = "hello world";
String s2 = "hello world";
System.out.println(s1==s2) // true
The above example returns true because the == operators checks if two references point to the same object. or not
Below how its looks Pictorially
The Eclipse Implementation ! I wanted to dive into check the memory adress of a variable visually so i used System.identityHashCode(Object obj) // this method return unique Integer values
领英推荐
The .equals() Method
.equals() method, on the other hand, is intended for content comparison. It is defined in the Object class and is meant to be overridden by subclasses to provide meaningful equality checks.
String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1.equals(str2)); // Output: true
In Java, the equals method in the Object class checks for reference equality, returning true only if both references point to the same object. In contrast, the String class overrides equals to first check for reference equality and, if they are different, then compare the content of the strings. The System.identityHashCode() method provides a hash code based on the object's memory address, which helps identify objects but does not directly compare their contents.
public boolean equals(Object obj) {
return (this == obj);
}
// default equals method in Object Class
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String) anObject;
return this.value.equals(aString.value);
}
return false;
}
// overidden .equal method in String class
java8|| DSA||Lld||systemdesign || springboot|| microservices || kafka|| upskilling atscaler
3 个月Love this
Software Engineer ? LinkedIn Top Problem Solving Voice '24 ? Open-source Contributor ? Core Java ? Data Structures and Algorithms ? MySQL ? Spring Boot ? Design Patterns ? Low-Level Design.
3 个月Useful tips Naveen Reddy ????