2

From the answer to a question about primitive types and autoboxing in java:

for biziclop:

class biziclop {

public static void main(String[] args) {
    System.out.println(new Integer(5) == new Integer(5));
    System.out.println(new Integer(500) == new Integer(500));

    System.out.println(Integer.valueOf(5) == Integer.valueOf(5));
    System.out.println(Integer.valueOf(500) == Integer.valueOf(500));
}

}

Results in:

C:\Documents and Settings\glow\My Documents>java biziclop
false
false
true
false

C:\Documents and Settings\glow\My Documents>

Why is that?

Community
  • 1
  • 1
steps
  • 618
  • 1
  • 7
  • 18

4 Answers4

3

Integer.valueof caches objects for values around zero as required by the Java Language Specification.

Inspired by ilya's answer see the latest, actual source for Integer.valueOf() in the upcoming JDK7, lines 638-643.

Community
  • 1
  • 1
Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
3

See Integer.valueOf realization: http://docjar.com/html/api/java/lang/Integer.java.html (850s line)

ilalex
  • 3,018
  • 2
  • 24
  • 37
1

You should use the equal method not the == operator. == test if two objects are equal but you create different objects with same value and need the equal() method to compare the object's values.

Update:
Reason for different behavior of Integer.valouOf(5) and Integer.valouOf(500) is indeed that Integer implementation uses a static valueOfCache of size -128..127.
As of Java 7 this is configurable with the command-line argument -XX:AutoBoxCacheMax=<size>

bw_üezi
  • 4,483
  • 4
  • 23
  • 41
  • I didn't intend to compare the values but was looking for an explanation as to why the results of the two comparisons are different while they seem to be doing the same thing. – steps Mar 08 '11 at 21:32
1

Integer.valueOf caches values, specifically -128 to 127.

Robby Pond
  • 73,164
  • 16
  • 126
  • 119