Where are int and Integer Objects values ​​stored?

When we initialize some integer values, such as

int a = 10; 

or

 Integer b = new Integer(20); Integer b = 30; 

Where are those objects that were created in memory?

Is there any concept like Integer-Pool, how do we have String-Pool for String?

+4
source share
3 answers

Most JVMs (even 64-bit) use 32-bit links. (New JVMs use 32-bit links for heaps up to almost 32 GB). The link is on the stack or in the CPU register and is usually not counted. An 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 on the stack to hold the reference value and is initialized to zero

new creates an instance in heap memory

+2
source

Objects created with the new keyword are stored on the heap.

Variables (references to these objects) and primitive types such as int are stored in the program stack.

Integer not a special class in Java. You can use arithmetic operators with it, they are immutable, and you can even use == to test equality (in the range of -128 to 127, since these values ​​are already cached).

Is there any concept like Integer-Pool, how do we have String-Pool for String?

Open the java.lang.Integer code and look at the valueOf method. Obviously, they really use the 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); } 

In addition, I think this image will be useful to you:

enter image description here

0
source

Integer in the range from -128 to +127 are pre-created. You may think that they are in a “whole pool”.

At run time, any other value is created.

This leads to some subtle behavior in Java:

The expression boo == far for the two values ​​of Integer foo and bar will be true if their values ​​are equal and are in the range from -128 to +127. This will not be true for values ​​outside this range: you need to use .equals for such values.

Personally, I find it detrimental: Never use == for nested types.

-one
source

All Articles