== operator for primitive data types [duplicate]

2019-04-11 23:37发布

问题:

Possible Duplicate:
How Does the toString(), ==, equals() object methods work differently or similarly on reference and primitive types?

I am trying to understand the difference between == and equals to operator in Java. e.g. == will check if it is the same object while equals will compare the value of the object ... Then why do we use == for comparing primitive data types like int. Because if I have

   int i =7; //and 
   int j = 6. 

They are not the same object and not the same memory address in stack. Or does the == behaves differently for primitives comparison.??

回答1:

Actually, == behaves identically for all variables: it tests whether the values of those variables are equal. In the case of Object obj, obj is a reference to an object. Since == tests whether two object references have the same value, it is testing whether they refer to the identical object (i.e., that the references are equal).



回答2:

== intuitively work differently on primitive types. Its just that way in the language.

If you think about it in C++ terms, references are pointers and == does pointer comparison.

int* myPtr1 = new int(5);
int* myPtr2 = new int(6);

myPtr1 == myPtr2;