Boxing of an Integer and conservation of space in Java


Apparently, boxing of an int literal initialization into an Integer class will result in two different objects being assigned the same space in memory if the number is 127 or smaller, but different spaces in memory if the number is 128 or larger.

Take BoxTest.java:


public class BoxTest {
public static void main(String [] args) {
// These two objects will occupy different spaces in memory.
Integer i1 = 128;
Integer i2 = 128;

System.out.println("i1 = " + i1 + ", i2 = " + i2 + " => ");
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");

// These two, smaller objects, will occupy the same space in memory.
Integer i3 = 127;
Integer i4 = 127;

System.out.println("i3 = " + i3 + ", i4 = " + i4 + " => ");
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");
}
}

The output:

[~/Dropbox/java/tech0x20] javac BoxTest.java
[~/Dropbox/java/tech0x20] java BoxTest
i1 = 128, i2 = 128 =>
different objects
meaningfully equal
i3 = 127, i4 = 127 =>
same object
meaningfully equal

One response to “Boxing of an Integer and conservation of space in Java”

Leave a Reply

%d bloggers like this: