Why same integer value have different memory address in Java?

java, memory

Solution

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. ;)

Problem

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?

Original source

Related problems