Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer == int allowed in java

Tags:

java

int

equals

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?
}
like image 436
Franz Kafka Avatar asked Oct 06 '11 09:10

Franz Kafka


1 Answers

Yes, when comparing int using == arguments will be unboxed if necessary.

Relevant section from the Java Language Specification:

15.21.1 Numerical Equality Operators == and !=

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then an integer equality test is performed; if the promoted type is float or double, then a floating-point equality test is performed.

Note that binary numeric promotion performs value set conversion (§5.1.13) and unboxing conversion (§5.1.8). Comparison is carried out accurately on floating-point values, no matter what value sets their representing values were drawn from.

Same applies for <, <=, >, >= etc, as well as +, -, * and so on.

So,

System.out.println(Integer.valueOf(17) == 17);

prints true :-)

but you can compare two equal strings with == and sometimes get true or fals depending on how the strings were pooled...

Right, and there is actually a similar situation for Integers as well.

When boxing (transforming int to Integer) 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:

System.out.println(Integer.valueOf(100) == Integer.valueOf(100)); // prints true
System.out.println(Integer.valueOf(200) == Integer.valueOf(200)); // prints false
like image 180
aioobe Avatar answered Oct 21 '22 05:10

aioobe