Puzzler # 8
Jun. 16th, 2005 05:34 pmI have to apologize for skipping the puzzlers that I forgot... now, here's the best one.
What will the program print:
a) "Of all numbers, the most important for us is 0"
b) "Of all numbers, the most important for us is 21"
c) "Of all numbers, the most important for us is 42"
d) Exception is thrown
e) None of the above
Enjoy...
/* source: "Java Puzzlers" by Josh Bloch and Neal Gafter*/
public class Puzzler8 {
// incredibly lazy initialization
public static int importantValue = 0;
private static boolean isInit = false;
static void init() {
importantValue = 21;
Thread t = new Thread(
new Runnable() {
public void run() {
importantValue = 42;
isInit = true;
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
static {
init();
}
public int getValue() {
return importantValue;
}
public static void main(String[] args) {
System.out.println("Of all numbers, the most important for us is " + new Puzzler8().getValue());
}
}
What will the program print:
a) "Of all numbers, the most important for us is 0"
b) "Of all numbers, the most important for us is 21"
c) "Of all numbers, the most important for us is 42"
d) Exception is thrown
e) None of the above
Enjoy...