When 1 + 1 = 3

March 24, 2020 | 2 Minute Read

I was looking at some old gists of mine yesterday and I found one that I thought it was worth sharing. It’s not something new for anyone who has been using Java for some time probably, but it’s one of those things newcomers get amazed every time.

For this we are going to use the ‘new’ java REPL (you need java 9 or newer) as it’s easier than setting up a full maven/gradle project.

So, in what consists this ‘trick’ we are talking about? You are probably familiar with the expression 1 + 1 = 2 right? Which is usually applied to explain simple situations.

Well, Java says otherwise…

jshell> 1 + 1
$6 ==> 3

And how is this possible? To understand how this works, we need to get a bit into the internals of the Integer class.

The current Integer class implementation contains a cache, which was introduced to save memory and to improve performance for Integer type objects handlings. Integer instances are cached and reused. The blog Javapapers has an excellent article on the topic. It’s a quick read, and it will explain IntegerCache much better than me :)

Now back to our little dark magic. The trick here is to mess with the IntegerCache through reflection. By changing the cache value for a given int, you will be able to do all sort of hacks.