1

On reading many articles I could figure out that == compares if the two operands are referring to same object.

How does it work with primitive data types.

Does it compare the values of the operand?

Does == work differently for primitive data types and classes ?

Kindly clarify

3 Answers3

2

primitives are not Objects, and thus do not have a equals(...) method. The only way to compare primitives for equality is to use the == operator.

Note that comparing double and float values can be tricky with ==.

rolfl
  • 17,539
  • 7
  • 42
  • 76
1

The “==” operator is actually checking to see if the string objects (obj1 and obj2) refer to the exact same memory location. In other words, if both obj1 and obj2 are just different names for the same object then the “==” operator will return true when comparing the 2 objects.

The equals() method actually behaves the same as the “==” operator – meaning it checks to see if both objects reference the same place in memory. But, the equals method is actually meant to compare the contents of 2 objects, and not their location in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.

primitive data types can not be compared using equal() as they are not objects. int, char can be compared using == operator.

But when you compare float and double you may get different results due to binary conversion in machine. So when comparing float values, to be consistent for all values, including the special Float.NaN value, Float.compare() is the best option. same applies to double values.

Blackhat002
  • 598
  • 4
  • 12
  • From your statement, “==” compares the objects referring to same memory location. But what about primitive data type, where we don't have any objects. We just compare values using “==” for primitive data types? unlike objects. – user3163483 Oct 07 '14 at 04:34
  • Yes, Exactly for objects use equals () and for primitives '==' operator. – Blackhat002 Oct 07 '14 at 05:36
0

For primitive data types, you should use ==, which merely compares the values of the two given parameters.

For boxed primitive data types, such as Long, Double, Integer, you should use equals for the comparison. If == is used, it only compares the referential equality.

Byungjoon Lee
  • 913
  • 6
  • 18
  • So, when we compare two primitive data types, == compares the operand value. But when we compare two objects, == compares reference? WOuld that be a right statement? – user3163483 Oct 07 '14 at 04:23
  • In some sense, you can think the reference as the in-memory address of the object. Thus, if you accept the `==` always compares the values of the two given operands, you can think that `==` also can be used to compare the two references are pointing to the same objects. – Byungjoon Lee Oct 07 '14 at 04:25