7

I have this Java code:

public class Foo {
    public static void main(String[] args) {
         Integer x = 5;
         Integer y = 5;
         System.out.println(x == y);
    }
}

Is it guaranteed to print true on the console? I mean, is it comparing the two boxed integers by value (which is what I need to do) or by reference identity?

Also, will it be any different if I cast them to unboxed integers like this

public class Foo {
    public static void main(String[] args) {
         Integer x = 5;
         Integer y = 5;
         System.out.println((int) x == (int) y);
    }
}
9
  • 5
    It is comparing them by reference identity. Integers in the range -128 to 127 are cached, which is why Integer instances are sometimes the same reference. But you are better off using equals. Commented Mar 14, 2019 at 16:14
  • 1
    the thing is that if I write (int) x == (int) y the IDE (I'm using intellijIdea) tells me that the cast is unnnecessary Commented Mar 14, 2019 at 16:15
  • 1
    If needed you can do x.intValue() == y.intValue(), but it is better to just use x.equals(y) Commented Mar 14, 2019 at 16:17
  • 4
    @oggioniw If either might be null, you need to null-check it (or use Objects.equals). Using .equals or .intValue() or (int) all risk raising a NullPointerException. Commented Mar 14, 2019 at 16:22
  • 1
    @khelwood +1 for suggesting usage of Objects.equals Commented Mar 14, 2019 at 16:26

2 Answers 2

15

No, it's not the right way to compare the Integer objects. You should use Integer.equals() or Integer.compareTo() method.

By default JVM will cache the Integer values from [-128, 127] range (see java.lang.Integer.IntegerCache.high property) but other values won't be cached:

Integer x = 5000;
Integer y = 5000;
System.out.println(x == y); // false

Unboxing to int or calling Integer.intValue() will create an int primitive that can be safely compared with == operator. However unboxing a null will result in NullPointerException.

Sign up to request clarification or add additional context in comments.

3 Comments

what if I cast them to unboxed integers like this (int) x == (int) y?
For full answer, mention use of Objects.equals as commented by khelwood as solution to null issue.
Also cache range is configurable since Java7
0

No it is not the right way to compare to object directly.You can convert to int value and compare.

Java implementation

Where value is of type int.

public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.