Why in the below code is assigning a value to the static variable acceptable but using that same variable is not?
class Test
{
static
{
var=2; //There is no error in this line
System.out.println(var); //Why is there an error on this line if no error on the above line
}
static int var;
}
A static method manipulates the static variables in a class. It belongs to the class instead of the class objects and can be invoked without using a class object. The static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded.
Variables declared inside a block are accessible only inside of that block. Static or no. Variables declared inside a static method are static. They can only access other static variables or global variables.
In a Java class, a static block is a set of instructions that is run only once when a class is loaded into memory. A static block is also called a static initialization block. This is because it is an option for initializing or setting up the class at run-time.
You can declare a variable static inside a static block because static variables and methods are class instead of instance variable and methods. This means that you wont be able to see a static field inside a method because it will be inside an inner scope and won't be a class variable at all...
The error you get is Test.java:6: illegal forward reference
. Move the int var
before the static block.
Because the usage is not on the left hand side of an assignment, as explained below:
From section 8.3.2.3 of the JLS, Restrictions on the use of Fields during Initialization:
The declaration of a member needs to appear before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
The usage occurs in an instance (respectively static) variable
initializer of C or in an instance (respectively static) initializer
of C.The usage is not on the left hand side of an assignment.
C is the innermost class or interface enclosing the usage.
A compile-time error occurs if any of the three requirements above are not met.
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