When we initialize some integer values like
int a = 10;
or
Integer b = new Integer(20);
Integer b = 30;
where are those objects created in memory?
Is there any concept like Integer-Pool like we have String-Pool for String?
When we initialize some integer values like
int a = 10;
or
Integer b = new Integer(20);
Integer b = 30;
where are those objects created in memory?
Is there any concept like Integer-Pool like we have String-Pool for String?
Most JVMs (even 64-bit ones) use 32-bit references. (Newer JVMs uses 32-bit references for heaps up to almost 32 GB) The reference is on the stack or in a CPU register and is not usually counted. The Integer is allocated on the heap.
Integer i = new Integer(1); // creates a new object every time.
Integer j = 1; // use a cached value.
Integer a;
will allocate memory in stack to hold the reference value and initialized with null
new
creates instance in heap
memory
Objects created with new
keyword are stored on heap.
Variables (references to those objects) and primitive types like int
are stored on program's stack.
Integer
is not a special class in Java. You can use arithmetic operators with it, it's immutable and you can even use ==
for equality testing (in the range of -128 to 127 since those values are already cached).
Is there any concept like Integer-Pool like we have String-Pool for String?
Open the code of java.lang.Integer
and look at the valueOf
method. It's obvious that they indeed use an Integer pool.
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
Also, I think this image will be helpful for you:
Integer
s in the range -128 to +127 are pre-created. You can think of those as being in an "integer pool".
Any other value is created at runtime.
This leads to some subtle behaviour in Java:
The expression boo == far
for two Integer
values foo
and bar
will be true
if their values are equal and in the range -128 to +127. It will not be true for values outside that range: you need to use .equals
for such values.
Personally I find that pernicious: Never use ==
on boxed types.