how equal operator works with primitive and object type data

前提是你 提交于 2019-11-27 23:41:30

问题


I know its a very basic question but I want to be clear about the concept. I want to know how == operator works in case of primitive and object type. For example

Integer a = 1;
int b = 1;
System.out.println(a == b)

how a is compared with b, whereas a contain the ref of object that contains value 1. Can somebody clearify it to me how it works internally?


回答1:


In general the equality operator in Java performs a so called shallow comparison. In other words it compares the values that variables contains. Now the variables of primitive data types contains the value itself while the reference types contains reference to heap area which stores the actual content. That means that in your code snippet int b will hold value 1 and Integer a will hold the memory address of the actual Integer object on the heap.

Now in the particular example provided by you there is one pecularity. Integer class a special wrapper class that wraps primitive integer types. The compiler can automatically convert between such wrapper objects and primitive types (which is called boxing and unboxing).

Let's walk you code step by step tgo make it clear.

Integer a = 1;

The compiler actually substitue the following code insted of this line:

Integer a = Integer.valueOf(1);

The static method valueOf returns an wrapper object instance that wraps the provided primitive value. This procedure when the compiler constructs a wrapper class out of a primitive type is called boxing.

When using such a wrapper object is compared with with a primitive variable using equality operator

a == b

the compiler actually changes it to the following:

a.intValue() == b;

where intValue returns the primitive value wrapped by the wrapper object (which is called unboxing) i.e. it unboxes the primitive value and make the expression equivalent to comparing two primitives. This is why the equality operator then returned true




回答2:


In your particular example boxed type Integer will be unboxed to a primitive type int and == will compare primitives (i.e. true in your case).



来源:https://stackoverflow.com/questions/29139274/how-equal-operator-works-with-primitive-and-object-type-data

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