Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Integer objects [duplicate]

Tags:

java

object

oop

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?

like image 340
Luke Taylor Avatar asked Sep 22 '12 19:09

Luke Taylor


People also ask

How do you compare integer objects?

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 .

Can you use == to compare objects?

The == operator compares whether two object references point to the same object. For example: System. out.

Can we compare double with int?

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.

Can you use == to compare integers?

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).


1 Answers

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.

like image 150
meriton Avatar answered Sep 17 '22 22:09

meriton