Java Coding Nerd. This Blog will feature content-rich articles, tutorials and own opinions on variuos programming related topcis.

Java Riddles

Java Riddle: How come that 1+2 = 4

Java Riddle Hello World

Java Riddle

I agree, the title of this Blog-entry might sound a bit nuts. But it is a Riddle.We all know that 1+2 = 3 But what if i tell you, that we as devs can change those old laws that rule our world.
First have look at this little code snippet and try to solve the Riddle

public class ReflectionsRiddle {

public static void main(String[] args) throws Exception {

//Write your code here

Integer first = 1;
Integer second = 2;

System.out.println("1 + 2 = " + (first + second));


So if you run this code your console will print the obvious. 1 + 2 = 3. Now think of what you can code to make the output 1 + 2 = 4. BUT you are only allowed to put your code where the comment tells you to write it. Don`t alter the existing Code!!!!

You need some advice?

Mark the Whitespace to see the advice

1.  this Riddle cant be solved wont work if we use the primitive int type
2.  ever heard about reflections?
3.  no? than make sure to check this out /Field.html
4. java caches Integer values from -128 to 127

Solving the Riddle

The code you have to add above the exisiting is the following:

//Write your code here
Field value = Integer.class.getDeclaredField("value");
value.set(1, 2);

Paste it into your project and check if the output is 4. So what happened here?
Using Reflections allowed us to change the entry for the value 1 in the jvm default caching system. Therefore we retrieve the value 2 if we set Integer to 1.
There is an easy way to proof our assumption. Change the code from
Integer first = 1 to Integer first = new Integer(1).
Eventhough we changed the value in the cache the output will be 3 again.
We did not refere to the cache entry, but declared a new Integer Object which has its own value(i.e. 1)

There you go.

Spread the love

Leave a Reply

Theme by Anders Norén