Wednesday, September 28, 2005

Java Puzzlers - Can you figure this out?

The book Java Puzzlers is quite good. I don't think anyone can get every puzzle right. This shows again how you can very easily make someone fail interviews if you ask too silly questions. I suppose that if people were asking those questions they would not expect the right answers, but study the candidate reactions.

Here is a sample:

public class DosEquis {
  public static void main(String[] args) {
    char x = 'X';
    int i = 0;
    System.out.print(true ? x : 0);
    System.out.print(false ? i : x);
  }
}


This will output "X88". Obviously this is not good code, which is precisely one of the book objectives: to show how bad some practices can be. But at the same time you learn a bit more about the Java language and its possibilities. In the latter chapters they have more interesting puzzles.

Tags: , ,

2 comments :

  1. As with many of the puzzles in the book, the answer to this puzzle is type promotion. In the second print statement, the character 'X' is promoted to an int since the other argument is an int.

    ReplyDelete
  2. This is not fully correct. There is here an additional twist.
    System.out.println(false?0:x) will output "X" while 0 is an int in this case. The thing is that conditional expressions behave differently if a constant is passed or a variable. If it is a variable, there is promotion.

    ReplyDelete