Difference between == and equals method is not one of the most frequently asked question in java developer interview. However, we should know the concept of equals() method and == operator in java.
In other words ,
Example 1:
in the above code, i == j is true because both i and j refer to the same object.
Example 2:
In the above code, i == j is false because, although they both have the value 10, they are two different objects.
Recap: Difference between == and equals() method in java
In other words ,
Example 1:
Integer i = new Integer(10);
Integer j = i;
in the above code, i == j is true because both i and j refer to the same object.
Example 2:
Integer i = new Integer(10);
Integer j = new Integer(10);
In the above code, i == j is false because, although they both have the value 10, they are two different objects.
Recap: Difference between == and equals() method in java
== | equals() | |
---|---|---|
Primitives or Objects | Primitives | Object |
Type | binary operator | Method |
Comparison | Based on Memory reference | Based on values |
That's it for today, please mention in comments if you have any questions regarding difference between == and equals() method in java.