Here is the straightforward breakdown of the difference between the two:
The == Operator (Reference Comparison)
- What it does: For objects, it checks if two variables point to the exact same object in memory (the same memory address).
- For Primitives: If you are comparing primitive data types (like
int,double, orboolean),==simply compares their actual numerical or boolean values.
The .equals() Method (Value Comparison)
- What it does: It evaluates the actual content inside the objects to see if they are logically identical.
- How it works: Classes like
StringandIntegerare specifically programmed to check the data inside them when.equals()is called. If you create your own custom class, you have to write (override) the.equals()method yourself to tell Java exactly what makes two of your objects “equal.”
Quick Code Example
Java
String str1 = new String("java");String str2 = new String("java");String str3 = str1;// Using ==System.out.println(str1 == str2); // FALSE: They contain the same text, but are two completely separate objects in memory.System.out.println(str1 == str3); // TRUE: They point to the exact same memory location.// Using .equals()System.out.println(str1.equals(str2)); // TRUE: Their actual text content ("java") is exactly the same.
Leave a Reply
You must be logged in to post a comment.