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);
}
}
Java Integer compare() method public static int compare(int x, int y) Parameter : x : the first int to compare y : the second int to compare Return : This method returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero.
It is valid, but you may get interesting results in edge cases if you don't specify a precision on the double...
To check two numbers for equality in Java, we can use the Equals() method as well as the == operator. Firstly, let us set Integers. Integer val1 = new Integer(5); Integer val2 = new Integer(5); Now, to check whether they are equal or not, let us use the == operator.
Integer Equals() method in JavaThe Equals() method compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With