Explanation
As written in the JLS, fields are always automatically initizialized to their default value, before any other assignment.
The default for int
is 0
. So this is actually part of the Java standard, per definition. Call it magic, it has nothing to do with whats written in the constructor or anything.
So there is nothing in the source code that explicitly does this. It is implemented in the JVM, which must adhere to the JLS in order to represent a valid implementation of Java (there are more than just one Java implementations).
See §4.12.5:
Initial Values of Variables
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2)
Note
You can even observe that this happens before any assignment. Take a look at the following example:
public static void main(String[] args) {
System.out.println("After: " + x);
}
private static final int x = assign();
private static int assign() {
// Access the value before first assignment
System.out.println("Before: " + x);
return x + 1;
}
which outputs
Before: 0
After: 1
So it x
is already 0
, before the first assignment x = ...
. It is immediatly defaulted to 0
at variable creation, as described in the JLS.