Java integer cache

  • warning: include(/tmp/fortune.txt): failed to open stream: No such file or directory in /home/mohawksoft/org/www/htdocs/includes/common.inc(1696) : eval()'d code on line 1.
  • warning: include(): Failed opening '/tmp/fortune.txt' for inclusion (include_path='.:/usr/share/php:/usr/share/pear') in /home/mohawksoft/org/www/htdocs/includes/common.inc(1696) : eval()'d code on line 1.

Normally, comparing objects, as in this example

public class test
{
	public static void main (String args[])
 	{
		Integer a = 5;
		Integer b = 5;
		Integer c = 2000;
		Integer d = 2000;

		if(a == b)
			System.out.println("a==b");
		else
			System.out.println("a!=b");
		if(c==d)
			System.out.println("c==d");
		else
			System.out.println("c!=d");
	}
}

Fails as the reference to the object is checked for equality, not the contents. So you'd expect the output of the program to be

a!=b
c!=d

But you actually get

a==b
c!=d

This is because Java implements a cache of about 256 Integer objects from -128 to 127. Every time your program calls ValueOf() for an Integer, and the value is in this range, you will get the same Integer object and the reference, not the value, tests for equality.