I have the following code:
public class Test { public static void main(String[] args) { Integer alpha = new Integer(1); Integer foo = new Integer(1); if(alpha == foo) { System.out.println("1. true"); } if(alpha.equals(foo)) { System.out.println("2. true"); } } }
The output is as follows:
2. true
However changing the type of an Integer object
to int
will produce a different output, for example:
public class Test { public static void main(String[] args) { Integer alpha = new Integer(1); int foo = 1; if(alpha == foo) { System.out.println("1. true"); } if(alpha.equals(foo)) { System.out.println("2. true"); } } }
The new output:
1. true 2. true
How can this be so? Why doesn't the first example code output 1. true
?
Using the . equals() method, you actually compare the values/properties of objects, not their location in memory: new Integer(1) == new Integer(1) returns false , while new Integer(1). equals(new Integer(1)) returns true .
The == operator compares whether two object references point to the same object. For example: System. out.
It is valid, but you may get interesting results in edge cases if you don't specify a precision on the double... With the caveat from @PinnyM, I should point out that converting int to double is lossless, but promoting long to double is lossy.
To compare integer values in Java, we can use either the equals() method or == (equals operator). Both are used to compare two values, but the == operator checks reference equality of two integer objects, whereas the equal() method checks the integer values only (primitive and non-primitive).
For reference types, ==
checks whether the references are equal, i.e. whether they point to the same object.
For primitive types, ==
checks whether the values are equal.
java.lang.Integer
is a reference type. int
is a primitive type.
Edit: If one operand is of primitive type, and the other of a reference type that unboxes to a suitable primitive type, ==
will compare values, not references.
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