Autoboxing

What will be the output of the following Java code -

1
2
3
4
Integer a = 100, b = 100;
System.out.println(a == b);
Integer c = 200, d = 200;
System.out.println(c == d);

Details and Assumptions

  • Ignore the line break in the print statement.
  • Code is only tested for Java 5+.
False True True True False False True False Compilation Error Runtime Error

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

Arulx Z
Nov 24, 2015

Integer is not a primitive type and it shouldn't be compared using == . The == comparison only works when the references of both objects are same.

Java caches the values of integers from -128 to 127. Hence a == b have the same reference due to Java's mechanisms. So the answer returned is true .

However in case of 300 (which is outside the range of -128 to 127), the values are not cached. Hence two objects having the same value may* have different references. Hence c == d returns false.

1
a.equals(b)

must be used to compare two objects.


Note: two objects outside the range of -128 to 127 may have the same reference. However the probability is low.

Moderator note:

This is quite peculiar. I didn't know about this behavior.

Well, I learnt something new today. Nice! +1 :)

Prasun Biswas - 5 years, 6 months ago

[This is not a solution]

I've heard that Java cache's values from [-128,128] to prevent recomputation and etc. I have very little Java knowledge, but this feels like nonsense.

Please tell me how this works

This blog might be helpful.

Arulx Z - 5 years, 6 months ago

Log in to reply

From what I've understood,

Integer is not a primitive type and == should not be used to compare them.

Integers from -128 to 127 are cached by Java and hence for values of i and j (Note: i = j ) within the range, i == j will always return the same reference. Integers outside of the limits may not do so. So for j and k (Note: j = k ) outside the range, j == k may not return true.

Arulx Z - 5 years, 6 months ago

Log in to reply

It's important to note that i == k will only return true if i = k and they both have the same referance.

Arulx Z - 5 years, 6 months ago

Log in to reply

@Arulx Z If Integer isn't a primitive type, what is?

Agnishom Chattopadhyay - 5 years, 6 months ago

Log in to reply

@Agnishom Chattopadhyay It's a class that wraps int primitives into an object.

Arulx Z - 5 years, 6 months ago

Log in to reply

Haha. C is the best after all.

Arulx Z - 5 years, 5 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...