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?
All Java integer types are stored in signed two's complement format. The sign takes up one bit. The remaining bits store the value itself and dictate the range of values that can be stored for each type. For example, a short value uses one bit for the sign and 15 bits to store the value.
An object of the Integer class can hold a single int value. Constructors: Integer(int b): Creates an Integer object initialized with the value provided.
An object of type Integer contains a single field whose type is int . In addition, this class provides several methods for converting an int to a String and a String to an int , as well as other constants and methods useful when dealing with an int .
The Java int keyword is a primitive data type. It is used to declare variables. It can also be used with methods to return integer type values. It can hold a 32-bit signed two's complement integer.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With