If a static variable is in RIWO (Read Indirectly Write Only) state. the static variable can not be accessed directly.
here is the code
class Test {
static{
System.out.println(x);
}
static int x = 10;
public static void main(String[] args) {
}
}
in this case illegal forward reference compile time error is coming.
but if you are using the class name to access the static variable, it can be accessed.
here is the code example
class Test {
static{
System.out.println(Test.x);
}
static int x = 10;
public static void main(String[] args) {
}
}
answer is : 0
how is this possible ? isn't this a direct access ?
Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
The difference between static global variables and static local variables is that a static global variable can be accessed from anywhere inside the program while a static local variable can be accessed only where its scope exists (i.e block scope).
An instance variable, as the name suggests is tied to an instance of a class. Therefore, accessing it directly from a static method, which is not tied to any specific instance doesn't make sense. Therefore, to access an instance variable, we must have an instance of the class from which we access the instance variable.
non-static methods can access any static method and static variable also, without using the object of the class. In the static method, the method can only access only static data members and static methods of another class or same class but cannot access non-static methods and variables.
As per JLS 12.4.1. When Initialization Occurs and this answer:
a class's static initialization normally happens immediately before the first time one of the following events occur:
- an instance of the class is created
- a static method of the class is invoked
- a static field of the class is assigned
- a non-constant static field is used
In your case reading Test.x
falls under point 4, a non-constant static field. Your code reads and output 0
which is the default int
value, however you change it by marking the field final
as
static {
System.out.println(Test.x);
}
final static int x = 10;
The code will now output 10
. You can see it by comparing output of javap -c Test.class
for both non-final and final field cases, the order of bytecode will be reversed around:
6: invokevirtual #4 // Method java/io/PrintStream.println:(I)V
9: bipush 10
To me it looks like the Java compiler's forward reference error is a workaround for gotchas in static initialization in JVM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With