class revi {
static {
i = 3;
System.out.println("Hello World!");
}
static int i = 15;
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
above program does not give any error at i=3
; but when we call the i
in println()
method of static block it showing error
revi.java:6: error: illegal forward reference System.out.println("Hello World!"+i); ^ 1 error
class revi {
static {
i = 3;
System.out.println("Hello World!" + i);
}
static int i = 15;
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
but if modify the above program like this it working(static variable first loaded ) no error in println method
class revi {
static int i = 15;
static {
i = 3;
System.out.println("Hello World!" + i);
}
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
please explain internal flow ...
This is covered in section 8.3.3 of the JLS:
Use of class variables whose declarations appear textually after the use is sometimes restricted, even though these class variables are in scope (ยง6.3). Specifically, it is a compile-time error if all of the following are true:
The declaration of a class variable in a class or interface C appears textually after a use of the class variable;
The use is a simple name in either a class variable initializer of C or a static initializer of C;
The use is not on the left hand side of an assignment;
C is the innermost class or interface enclosing the use.
In your case, all of them are true when you're printing the value, hence the error.
After changing your code to move the declaration, the first bullet is no longer true, so it compiles.
See more on this question at Stackoverflow