So I was just programming a bit, when I got some very unwanted behavior and found out something very weird about Java. Let's look at the (condensed) code:
public class Main {
static{
test = "test2"; // this is fine!?
System.out.println(test); //compilation error!
}
static String test = "test1"; // initialization line
public static void main(String[] args) {
System.out.println(test);
}
}
This program gives you a compilation time error saying that you can't reference "test" before it is defined. However I just did it exactly one line before. Now guess what is the output, when you comment out the error line...
The output is: "test1", so the initialization overwrites the assignment happening before the declaration!
Also if you don't initialize the variable, "test2" is the output. However, if you explicitly assign "null" as value during initialization, the output will be "null".
Questions:
- Why can I access a variable to write, but not to read, before it is declared?
- Why is the initialization done after the first assignment (this contradicts the term "initialization")?
- I always thought that explicitly initializing with "null" is the same as omitting the initialization. This is obviously wrong with this example. Was I just thinking the wrong thing or does this contradict the spec?
- Is this really the wanted Java behavior? Is it a bug?