3

I have the following lines of code in Java:

public class myProjects {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Integer d = Integer.MAX_VALUE;
    Integer e = Integer.MAX_VALUE;
    System.out.println(d);
    System.out.println(e);
    if(d == e){
        System.out.println("They are equal\n");

    }else {
        System.out.println("They are not equal\n");
    }
}

}

Output:
2147483647
2147483647
They are not equal

Why are they not equal even though they have the same value?

4 Answers4

3

Integer.MAX_VALUE returns an int. When doing Integer d = Integer.MAX_VALUE; it boxes the int to an Integer via Integer.valueOf.

Since by default the cache is from [-128, 127] valueOf will return new instance for each call. Thus they are not the same references.

You can see this in the generated bytecode:

public static void main(java.lang.String[]);
    Code:
       0: ldc           #3                  // int 2147483647
       2: invokestatic  #4                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       5: astore_1
       6: ldc           #3                  // int 2147483647
       8: invokestatic  #4                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;

and the source code of Integer.valueOf:

public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
0

You are comparing Objects, not primitives.

You should be using d.equals(e); instead of d == e

d == e evaluates whether or not the object is the same, and they are not.

Martin Hansen
  • 2,033
  • 1
  • 18
  • 34
0

Simply said, Integer is an Object and not a primitive value,

to check for equality of objects, you need to use equals method

e.g.

if(d.equals(e)) {....}
nafas
  • 5,283
  • 3
  • 29
  • 57
0

As sharonbn mentions in the comment.

Try changing

Integer d = Integer.MAX_VALUE;
Integer e = Integer.MAX_VALUE;

To

int d = Integer.MAX_VALUE;
int e = Integer.MAX_VALUE;

and see what happens.

km1
  • 2,383
  • 1
  • 22
  • 27