Java — == vs .equals()
String comparison in Java can lead to confusion, especially when using the == operator and the .equals() method. In this blog post, we will explore these concepts through practical examples.
The Basics of String Comparison
Java provides two primary ways to compare strings:
==Operator: Checks if two references point to the same object in memory..equals()Method: Checks if two strings have the same content.
Comparing String Literals
If we are creating string in java by using “ ” then only object will be get created inside the string pool and if we try to create more than one object with the same content then no other object will be created inside the string constant pool and no objects will be created inside java heap area as we are not doing any runtime stuff while creating string literal.
Get Deep Shah’s stories in your inbox
Join Medium for free to get updates from this writer.
So only one object is created using “ ” and that is in string constant pool and your string object reference will pointing to that object.
public class StringComparison {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1.equals(s2)); // true
System.out.println(s1 == s2); // true
}
}Explanation
- Using
.equals(): This method returnstruebecause boths1ands2contain the same characters. - Using
==: This also returnstruebecause boths1ands2reference the same string object in the string pool. Java optimizes memory usage by reusing string literals.
Comparing Two New String Objects
when we creating string in java by using new String(), total three objects are getting created,2 in the heap area and one inside the string pool. and each string reference will point to their individual object which is inside java heap area.
public class StringComparison {
public static void main(String[] args) {
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(s1.equals(s2)); // true
System.out.println(s1 == s2); // false
}Explanation
- Using
.equals(): This returnstrue, as both strings have identical content. - Using
==: This returnsfalse, as boths2ands1are different objects created with thenewkeyword, even though they contain the same characters.
Conclusion
- Use
.equals()for content comparison. - Use
==to check if two references point to the same object.
Understanding these differences is crucial for effective string manipulation and comparison in Java programming.
As always, feel free to share your opinion in the comments! See you next time.
Be sure to clap and follow the writer ️👏️️
Connect










