Sunday, June 29, 2008

Java Puzzles

Puzzle 1
Given the following code:
public class Puzzle 1 {
public static void main(String[] args) {
boolean b = false;
System.out.println("Output - " + ( b ? 1.66 : 2 ));
}
}

What is the output?
If you think, the output is "Output - 2" then you're wrong.
The right output is "Output - 2.0" because 1.66 is double, 2 is int so 2 is converted to double.

Puzzle 2
Given the following code:
public class Puzzle2 {
public static void main(String[] args) {
int i = Integer.valueOf("2*3");
System.out.println("Output - " + i );
}
}

What is the output?
java.lang.NumberFormatException is caused, because the parser methods accepts only literals in the String parameter.

Puzzle 3
Given the following code:
public class NullReference {

public static void doStuff() {
System.out.println("Hello");
}

public static void main(String[] args) {
((NullReference) null ).doStuff();

}

}

What is the output?
The output is:
Hello

because when we call a static method through an instance then the compiler determine the class and replace the instance reference to class reference.

No comments: