I was reading an interview with Joshua Bloch (from Effective Java fame) and it had this puzzle:
Josh’s Puzzle: “The Story of O”
The following Java program is not quite complete; it’s missing a parameter declaration for o. Can you provide a declaration that makes the program print “O noes!”? (The program must compile without generating any warnings.)
public class Story {
public static void main(String[] args) {
Object o = null;
story(o);
}
private static void story(<you provide the declaration> o) {
if (o != null)
System.out.println("O noes!");
}
The answer was in the comments and is
Object... - in other-words Varargs (http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html).
To understand why this is correct you need to look at what happens.
Object o = null; //this creates a reference that is pointed at null - it is still a reference however.
story(o); // this calls the story method that expects one or more Objects - it then constructs an array called o containing these object references
The array
o, inside the story method, is an array with one element - the reference to null. Therefore when it reaches the conditional:
if (o!=null), it evaluates as true because
o (in this context) is a reference to an instantiated array with 1 element - i.e. not null.
http://google-opensource.blogspot.co.uk/2011/04/geek-time-with-josh-bloch.html