== operator for primitive data types [duplicate]

余生长醉 提交于 2019-12-06 08:12:28

问题


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;


来源:https://stackoverflow.com/questions/7097886/operator-for-primitive-data-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!