简体   繁体   中英

How is memory allocated for “new Integer(1)” in Java?

I am little bit confused with java's memory allocation technique. Can anybody help me, how java will allocate memory for following code ?

Integer a;
a = new Integer(1);

I am asking that for Integer a , jvm will create 64 bit reference and a = new Integer(1) for that it will allocate more memory to store value of 1. Is this correct ?

Integer a; will allocate memory in stack to hold the reference value and initialized with null

new creates instance in heap memory

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.

Using auto boxing is not only shorter, but can be more efficient as it can use a cache.

Of course the most efficient is

int k = 1; // not object created and no heap used.

For autoboxed values the performance difference is very small compared with primitives and the reference is likely to be the same size as the int value. However for larger values, there can be a significant performance difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM