When going through the JLS 8.3.2.3 I wasn’t able to understand the following code.
class Z {
static { i = j + 2; }
static int i, j;
static { j = 4; }
}
The code is resulting in the error Cannot reference a field before it is defined
But if I change the code to
class Z {
static { i = 2; }
static int i, j;
static { j = 4; }
}
The code is getting compiled. But in both the cases the variable definition is after the initialization block. What is the mystery behind this?
You can assign to a value earlier than its declaration – you just can’t read it. So this fails too:
Whereas this is fine:
One of the four conditions in section 8.3.2.3 for an invalid usage is:
(The double-negatives in that section are making my head hurt, but I think it relevant!)
To be honest, that part of the spec is one of the worst I’ve seen – it’s really unclear. But the upshot is that you can assign but not read 🙂