This post originated from an RSS feed registered with Java Buzz
by Sam Dalton.
Original Post: Still More Programming Puzzlers Technical Session
Feed Title: import java.*;
Feed URL: http://www.samjdalton.com/pebble/rss.xml
Feed Description: Random, Infrequent Bloggings of a Techie
Still More Programming Puzzles was the best session I have been to yet. I was lucky enough to see Josh Bloch present a few years a go, so this was a session that I was determined not to miss.
The session presented 8 fiendish programming puzzles using the core Java API. Each problem had an obvious answer that was usually wrong, and the correct answers were at times surprising. Although the session was very light-hearted and presented in a jokey way, there was lots of useful stuff to take away (mainly in seeing what not to do.)
The first problem from the session is below along with the answer. I have noted down all of the other problems and may get around to posting them at a later date (probably as a PDF document.)
public class Puzzler {
public static void main(String args[]) {
long millis = 24 * 60 * 60 * 1000;
long micros = 24 * 60 * 60 * 1000 * 1000;
System.out.println(micros/millis);
}
}
So what does this print? You'd think it might print 1000 right? Wrong! It prints the unlikely value of 5. Basically what is going on here is that the value being assigned to micros is overflowing as you are performing integer arithmetic, and then casting to long. The value of 24 * 60 * 60 * 1000 * 1000 is 86400000000 which is beyond the size of the int type. In order to fix this program and make it print out 1000, you can simply change the assigment to long micros = 24L * 60 * 60 * 1000 * 1000. This converts the first value to long and thus long arithmetic is used. This was one of the easier problems to spot, some of the others were really sneaky!