how equal operator works with primitive and object type data

断了今生、忘了曾经 提交于 2019-11-29 06:12:17

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

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).

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