I was wondering if java automatically turns a Integer into an int when comparing to an int? Or will the == try and compare references on primitives?
Is this always true or do I need to do i.intValue()==2?
Integer i = Integer.valueOf(2);
if (i==2){
//always?
}
Yes, when comparing
intusing==arguments will be unboxed if necessary.Relevant section from the Java Language Specification:
Same applies for
<,<=,>,>=etc, as well as+,-,*and so on.So,
prints
true🙂Right, and there is actually a similar situation for
Integersas well.When boxing (transforming
inttoInteger) the compiler uses a cache for small values (-128 – 127) and reuses the same objects for the same values, so perhaps a bit surprising, we have the following: