Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Reflection and Integer Cache

DZone's Guide to

Reflection and Integer Cache

Free Resource

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

I was going thru the Reflection related articles and found the following code:

Field value = Integer.class.getDeclaredField("value");
value.setAccessible(true);
value.set(1, 2);
System.out.println(Integer.valueOf(1));
System.out.printf("5-4 => %d%n",5-4);
value.set(1001, 1002);
System.out.println(Integer.valueOf(1001));

The output was:

2
5-4 => 2
1001

I was surprised to see the results. I was expecting '1' but I got '2' in the first 2 cases. At least the 3rd result should have been 1002. I was totally wrong.

What's happening here?

Java autoboxing caches Integers -128 to 127 (It is because of this caching behavior few that people recommend using Integer.valueOf() instead of new Integer()).

The code used Reflection to change the value of the integer. As a result, the method Integer.valueOf(int i) returned the cached value (ie. modified value) and not the original value. This caused the above Java code's output to appear weird.

On a similar note the following code produced interesting output:

public class StringDestroyer {
public static void main(String[] args)
throws IllegalAccessException, NoSuchFieldException {
Field value = String.class.getDeclaredField("value");
value.setAccessible(true);
value.set("hello!", "cheers".toCharArray());
System.out.println("hello!");
}
}

Output:

cheers

Reference:

http://blogs.sun.com/darcy/entry/boxing_and_caches_integer_valueof
http://www.javaspecialists.eu/talks/oslo09/ReflectionMadness.pdf

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}