VOOZH about

URL: https://www.javacodegeeks.com/2015/01/my-favourite-java-puzzler-2-1-4.html

⇱ My favourite Java puzzler 2 + 1 = 4 - Java Code Geeks


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.

Reference: My favourite Java puzzler 2 + 1 = 4 from our JCG partner Daniel Shaya at the Rational Java blog.
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

πŸ‘ Photo of Daniel Shaya
Daniel Shaya
January 13th, 2015Last Updated: January 12th, 2015
3 125 1 minute read

Daniel Shaya

Daniel has been programming in Java since it was in beta. Working predominantly in the finance industry he has created real time trading and margin risk applications. He is currently a director at OpenHFT where we are building next generation Java low latency products.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

3 Comments
Oldest
Newest Most Voted
Jovaughn
11 years ago

This would of been really interesting if it was primitive values that were used.

0
Reply
10 years ago

Daniel, that was quite… puzzling :)

Have you read the Java Puzzlers book? There are many brain teasers in it. For example can you make this code become an infinite loop:

while (i == i + 1) {

}

Quite puzzling, huh? :)

If you’d like the answer and a few more puzzlers, I invite you to read more here: http://methodicalprogrammer.com/blog/5-puzzles-that-prove-you-need-to-read-java-puzzlers

0
Reply
haripriya
8 years ago

in my case output was 3 only. i am using jdk 904

0
Reply
Back to top button
Close
wpDiscuz