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);
}
}
-128to127are cached, which is why Integer instances are sometimes the same reference. But you are better off usingequals.(int) x == (int) ythe IDE (I'm using intellijIdea) tells me that the cast is unnnecessaryx.intValue() == y.intValue(), but it is better to just usex.equals(y)Objects.equals). Using.equalsor.intValue()or(int)all risk raising aNullPointerException.