A Puzzle from “A Brief History of the (Java) World and a Peek Forward” Presented by Neal Gafter

Here is a Java puzzle from Neal Gafter's presentation.

Which one is correct, a, b, c or d?

The answer is d.

There are 3 defects in this program:

1. Apparently, there is no "break" in the switch statement.

2. nextInt(2) will only return 0 or 1.

3. 'P', 'G', 'M' are Chars, not Strings. So it uses the wrong constructor.

There are more puzzles in the book below, if you want to do more.

Category >> Basics  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. leeyee on 2013-9-23

    I think this code output : “ain”, because StringBuffer(‘M’) is equivalent to StringBuffer(77). so in fact, StringBuffer(‘M’) call the constructor StringBuffer(int capacity)

    I have tested this code (Compiled using jdk6),it’s ran ok and output “ain”

Leave a comment