An odd case of initialization


You might assume that once a variable has been initialized it stays that way. However, the javac compiler, treats a variable as initialized only when it can determine a variable has been set, and exception handling can confuse the compiler.

But I know its initialised because I used it

In the following example, a variable is treated as initialized but after a catch block, the compiler isn't sure, and the variable can assigned again and used later.
int a;
try {
    a = 1;
    // a is initialised and can be read.
    System.out.println(a); // compiles ok.
} catch (RuntimeException ignored) {
// a is not considered initialised as the compiler 
// doesn't know the catch block couldn't be thrown before a is set.
System.out.println(a); // Variable 'a' might not have been initialized

a = 2;
// a is definitely initialised.
System.out.println(a); // compiles ok.

The problem here is that you know that the variable cannot throw an exception before the variable a is set, but the compiler doesn't know this. The simplest solution is to move the initialization out of the try/catch block.

Note: If you make the variable a final, the second a = 2 gets an error "Variable 'a' might have been initialized"


Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Comparing Approaches to Durability in Low Latency Messaging Queues