The Artima Developer Community
Sponsored Link

Java Buzz Forum
Still More Programming Puzzlers Technical Session

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
Sam Dalton

Posts: 143
Nickname: samd
Registered: Jun, 2003

Sam Dalton is a Java Developer with ThoughtWorks in teh UK
Still More Programming Puzzlers Technical Session Posted: Jun 30, 2004 12:53 AM
Reply to this message Reply

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
Latest Java Buzz Posts
Latest Java Buzz Posts by Sam Dalton
Latest Posts From import java.*;

Advertisement

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!

Read: Still More Programming Puzzlers Technical Session

Topic: Jabber and IM walled gardens Previous Topic   Next Topic Topic: The coolest talk at JavaOne

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use