You can tell whether it's legal or not by the fact that it compiles; unlike some other languages, Java doesn't have the notion of "undefined behavior." What happens here is completely spelled out. It may be counterintuitive, but it's specifically legal: you can access a static variable before it's initialized from a method called while initializing another static variable. The superficially similar case of accessing y
directly from x
's initializer -- i.e.,
private static int x = y;
private static int y = 5;
is specifically disallowed. There's really no strong reason why -- it's just how it is.