One thing to know where you declare static fields is that those are initialized in order; you cannot write:
public class DoesNotCompile
{
private static final int foo = 1 + bar; // ERROR: bar is not defined
private static final int bar = 1;
In your situation, however, things are a little different:
class Q26 {
// Declared first, but NOT first to be initialized...
public static Q26 q26 = new Q26();
public int ans;
// The honor befalls to this one, since it is declared `final`
private static final int var1 = 5;
private static int var2 = 7; // zero until initialized
public Q26() {
ans = var1 + var2;
}
}
The default value of a non initialized int is 0; since your Q26 instance is declared before var1 and var2, but since var1 is initialized first (since it is final), the result is what you see: ans is 5.
An equivalent to this code could be:
class Q26 {
public static Q26 q26;
private static final int var1;
private static int var2;
static {
var1 = 5;
q26 = new Q26();
var2 = 7;
}
public int ans;
public Q26() {
ans = var1 + var2;
}
}
Further note: there are also static initialization blocks; and order matters for these as well. You cannot do:
public class DoesNotCompileEither
{
static {
foo = 3; // ERROR: what is foo?
}
private static final int foo;
If you put the static initializer below the declaration of foo, then this will compile:
public class ThisOneCompiles
{
private static final int foo; // declared
static {
foo = 3; // initialized
}