Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where are int values and Integer Objects created?

Tags:

java

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?

like image 435
ParagFlume Avatar asked Aug 07 '15 11:08

ParagFlume


People also ask

Where are integers stored in Java?

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.

Can we create object of integer?

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.

What is an integer object?

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 .

Where is int used in Java?

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.


2 Answers

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

like image 119
Piyush Mittal Avatar answered Sep 29 '22 19:09

Piyush Mittal


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:

enter image description here

like image 33
darijan Avatar answered Sep 29 '22 18:09

darijan