Skip to content Skip to sidebar Skip to footer

Java Integers Return Strange Result While Compare Two Integers?

Integer i1= new Integer(9); Integer i2= new Integer(9); if(i1==i2){ System.out.println('true'); }else{ System.out.println('false'); } int

Solution 1:

First if-else print false. Why?

== checks if the two references are referring to the same object, in this case they are not so the == check is false. You need to use Integer.equals(), not ==:

if (i1.equals(i2){
    System.out.println("true");
}else{
    System.out.println("false");
}

Second return true

== is correct to use for primitives: int is a primitive.

third have true

As pointed out by JB Nizeti2 is unboxed to an int which makes the if condition a check between two int primitives.

Solution 2:

When == is used to compare references to objects, it returns true only if both references point to the same object.

In the first case, you have two different objects.

In the second case, you're not comparing objects, but primitive types.

In the third case, the Integer object is unboxed to its primitive int value to be compared with the primitive value, so two primitive values are compared.

You should never use == to compare objects, except for enums. Always use .equals().

Solution 3:

Whenever you use "==", you are doing a object reference check. That means, the first check will fail since they are 2 different objects.

In the second case, its straight forward.

In the third case, the compiler autoboxes "i2". So, the comparison will work fine.

Solution 4:

Remember you are not comparing 2 primitives but 2 Objects.. so Use .equals() method..

Solution 5:

The variables i1 and i2 refer to Objects, not primitive types. Using the == operator on objects in Java checks that the references are equal, if you want to compare them you should use the .equals() method.

The comparison of i3 and i2 returns true because you're comparing a primitive type (the int i3) with a wrapper class for that primitive type (the Integer i2), so Java unboxes the value of i2 to an int and then compares them (which does work with the == operator).

Post a Comment for "Java Integers Return Strange Result While Compare Two Integers?"