how equal operator works with primitive and object type data

Still Learning picture Still Learning · Mar 19, 2015 · Viewed 19.9k times · Source

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?

Answer

akhilless picture akhilless · Mar 19, 2015

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