+ 2

What's the difference in functions "==" operator and "equals" operator?

3rd Jun 2017, 3:53 AM
Mahesh Dudhnale
Mahesh Dudhnale - avatar
4 odpowiedzi
+ 4
To be more precise: On non-primitive data-types == compares the value of the reference of the objects. A reference is the location in memory that the object is stored in. If you do not want to compare equality by reference an alternative might be to use .equals(). In the example with Strings, .equals() is a method that will use a loop and compare character by character to check if each character is equal to the other, in order to determine equality. Returning true if they are equal. Generally if you ever want to compare self created objects you can override the equals() method and use whatever you want to compre them. However, for primitive data-types == will compare by value.
3rd Jun 2017, 4:40 AM
Rrestoring faith
Rrestoring faith - avatar
+ 3
I will explain String as example. Let's suppose I made a new String str as "Java" and str2 as "Java" with new operator. Two variables str and str2 have both "Java" as content. The method equals() gives us true since the content is same, but the location where those variables are saved is different. So == will gives us false. In other words, equals() gives true if content is same(can set when to give true if you are making a new class), but == gives true if two variables are exactly same.
3rd Jun 2017, 4:04 AM
OrbitHv [Inactive]
OrbitHv [Inactive] - avatar
+ 3
When using primitive data types like int, bool etc you can compare using == but when using Object types, such as a String, use the equals() method. Using == on an Object like a String will check if they are the exact same Object where using the equals() method will check if they have the same values.
3rd Jun 2017, 4:07 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
thank-you @Orb_H & chaoticdawg, means == compared pointers and equals() method compared values.
3rd Jun 2017, 4:10 AM
Mahesh Dudhnale
Mahesh Dudhnale - avatar