Sunday, 11 January 2015

My favourite Java puzzler 2 + 1 = 4 !!

Here's  my current favourite Java puzzler.

How can you get your code to do this?
Integer b = 2;
Integer c = 1;

System.out.println("b+c : " + (b+c) ); // output: 'b+c : 4' !!

There are no tricks with Sytem.out.println() i.e. you would be able to see the same value in a debugger.
Clue: You need to add a few lines of code somewhere before this in your program.

Scroll down for the solution.
.

.

.

.

.

.

.

.

.

.

.

public static void main(String... args)throws Exception{
        Integer a = 2;

        Field valField = a.getClass().getDeclaredField("value");
        valField.setAccessible(true);
        valField.setInt(a, 3);

        Integer b = 2;
        Integer c = 1;

        System.out.println("b+c : " + (b+c) ); // b+c : 4
}
As you can see (and I would encourage you to go to the source code for Integer) 
there is a static cache (look for the Inner class IntegerCache) where the value of the 
Integer is mapped to its corresponding int value.  The cache will store all numbers 
from -128 to 127 although you can tune this using the property  
java.lang.Integer.IntegerCache.high.

1 comment:

  1. 77%OFF Coach Outlet Store-Coach Bags Clearance Sale,100% Popular
    New & Popular Ray Ban Sunglasses Outlet Store Online,2020-2021 Stylish
    Clearance Coach Store | 80%OFF Coach Bags Outlet On Sale Online
    Share Best Best Adidas Yeezys Store|100% New & Real Yeezy Boost For Sale
    2020 Nike Air For 1 Shoes Outlet For Men & Women, 68-85%OFF Cheap Sale
    Official Michael Kors Outlet Store Online,100% Cheap MK Bags Sale
    61-82%OFF Air Jordan Shoe Stores|Cheap Jordans Releases,Hot Sale

    ReplyDelete