Wednesday, March 3, 2010

An Original Java Puzzler ...

Without further ado, what will be the output of the following program:

1 class ClassClass {
2 public static void main(String... args) {
3 System.out.println("Is Object.class instanceof Object?: " + Object.class instanceof Object);
4 System.out.println("Is Object.class instanceof Class?: " + Object.class instanceof Class);
5 }
6 }

Of course, I don't know if it is original or not. But I ran into it myself and thought of making it a puzzler :). Here are the options:
  1. Is Object.class instanceof Object?: false
    Is Object.class instanceof Class?: true
  2. Is Object.class instanceof Object?: true
    Is Object.class instanceof Class?: true
  3. Compiler error on line number 4
  4. Compiler error on both lines: 3 and 4
See first comment for answers.

1 comment:

  1. The correct answer is 3. The compiler (javac/Sun's JDK 1.6) helps you catch the errors as soon as they are committed. The line number 4 uses the operator precedence, the concatenation operator has higher precedence than instanceof and the left operand of instanceof evaluates to a String and a String can't be an instance of Class.

    However, line number 3 is not an error because String is always an instance of Object.

    (The compiler error message could be somewhat tricky).