Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static blocks and variables

Tags:

java

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;
}
like image 251
Lavneesh Avatar asked Aug 13 '11 06:08

Lavneesh


People also ask

What is static variable and static block?

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.

Can we declare variables in static block?

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.

What is static block?

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.

Are variables inside static block static?

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...


2 Answers

The error you get is Test.java:6: illegal forward reference. Move the int var before the static block.

like image 130
Jonathon Faust Avatar answered Oct 31 '22 04:10

Jonathon Faust


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.

like image 35
JRL Avatar answered Oct 31 '22 04:10

JRL