Java Reference
In-Depth Information
< Day Day Up >
Puzzle 52: Sum Fun
This program computes and caches a sum in one class and prints it from another. What does the
program print? Here's a hint: As you may recall from algebra, the sum of the integers from 1 to n is
n ( n + 1) / 2.
class Cache {
static {
initializeIfNecessary();
}
private static int sum;
public static int getSum() {
initializeIfNecessary();
return sum;
}
private static boolean initialized = false;
private static synchronized void initializeIfNecessary() {
if (!initialized) {
for (int i = 0; i < 100; i++)
sum += i;
initialized = true;
}
}
}
 
 
Search WWH ::




Custom Search