Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why same integer value have different memory address in Java? [duplicate]

Tags:

java

memory

Today is my first time to try Java language. When I try this code, I feel very strange:

int a =500;
System.out.println(System.identityHashCode(500));
System.out.println(System.identityHashCode(500));
System.out.println(System.identityHashCode(a));
System.out.println(System.identityHashCode(a));

All of these results is different. But when I changed 500 to 50, It become the same result.

Why is it?

like image 694
LeoShi Avatar asked Aug 09 '12 11:08

LeoShi


People also ask

Which takes more memory int or integer in Java?

As already mentioned int is a primitive data type and takes 32 bits(4 bytes) to store. On other hand Integer is an object which takes 128 bits (16 bytes) to store its int value.

How is integer stored in memory Java?

Integers are whole numbers which will be stored in computer using 4 bytes (32 bit) of memory.

What is memory address of object in Java?

To find the memory address of a particular object in the JVM, we can use the addressOf() method: String answer = "42"; System.out.println("The memory address is " + VM.current().addressOf(answer)); This will print: The memory address is 31864981224. There are different compressed reference modes in the HotSpot JVM.

How will you print the address of a variable without using a pointer in Java?

There is no way to get the memory address of anything in Java. All that is hidden by the JVM, you never have to worry about it. Even if you could get it, you couldn't do anything with it... Instead, you identify objects by other means, typically by implementing their equals() and hashCode() methods.


1 Answers

But when I changed 500 to 50, It become the same result.

Autoboxing caches the conversion of primitives to Object. Small values get the same object, larger values do not.

Note: while values between -128 and 127 are always cached, Higher values can be cached depending on command line settings. See the source for Integer for more details.

This is also called a Flyweight Pattern


You can set the maximum size of the Integer cache with

-Djava.lang.Integer.IntegerCache.high=NNNN
-XX:AutoBoxCacheMax=NNNN
-XX:+AggressiveOpts  // sets it higher depending on the version e.g. 10000

http://martykopka.blogspot.co.uk/2010/07/all-about-java-integer-cache.html

http://www.javaspecialists.eu/archive/Issue191.html

I feel very strange

I know what you mean reading this question. ;)

like image 169
Peter Lawrey Avatar answered Nov 14 '22 23:11

Peter Lawrey