Skip to main content
2 of 8
fix typos/grammar; separate and label warning message; minus sign

Java

Reflection is indeed the right way to go with abusing Java... but you need to go deeper than just tweaking some values. You need to change it even deeper than you can typically access. Note that this is designed for Java 6 with no funky parameters passed in on the JVM that would otherwise change the IntegerCache.

public class Main {
    public static void main(String[] args) throws Exception {
        Class cache = Integer.class.getDeclaredClasses()[0];
        Field c = cache.getDeclaredField("cache");
        c.setAccessible(true);
        Integer[] array = (Integer[]) c.get(cache);
        array[132] = array[133];

        System.out.println(Integer.valueOf(2 + 2));
    }
}

Output:

5

Deep within the Integer class is a Flyweight of Integers. This is an array of Integers from −128 to +127. cache[132] is the spot where 4 would normally be. Set it to 5.

Warning: Doing this in real code will make people very unhappy.

user12166