I was asked this question in an interview
If you do something like this,
private int c = d;
private int d;
It results in compile-time error that you
Cannot reference a field before it is defined.
Coming to the interview question,
1 public static int a = initializeStaticValue();
2 public static int b = 20;
3 public static int initializeStaticValue() {
4 return b;
}
5 public static void main(String[] args) {
System.out.println(a);
System.out.println(b);
}
I gave the same response as a gets initialised by a call to initializeStaticValue() where it is referencing an undefined value b.
But the programs works fine, gets compile, and prints
0
20
I am confused why
Cannot reference a field before it is defined.
was not thrown.
Secondly, when i debug it, why the control lands at
3 public static int initializeStaticValue() {
I mean, why this is the starting position of the program.
bis defined beforeinitializeStaticValue()so no error ofcannot reference a field before it is defined. 2. before you run yourmain(), your class needs to be loaded by JVM first, and you can treat the static field initialization is part of the load process, that's why yourinitializeStaticValue()starts before yourmain(). Is that what you are asking for?b'exists' as soon as the class is loaded. However it has not been assigned a value yet (so it has the default, which is why initializeStaticValue returns 0). The former case is a semantic language restriction because it never makes sense (and this behavior follows that for local variables, eg): however the compiler/language does not look into methods as these cases quickly become non-deterministic at compile time (see the halting problem).initializeStaticValue()is declared aftera, why compiler knows that it exists when it is on line 1?