Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java : accessing static variables inside static block

Tags:

Analyzing some weird scenarios in following static block :

static {   System.out.println("Inside Static Block");   i=100; // Compilation Successful , why ?   System.out.println(i); // Compilation error "Cannot reference a field before it is defined" }  private static int i=100; 

While same code is working fine while using :

static {   System.out.println("Inside Static Block");   i=100; // Compilation Successful , why ?   System.out.println(MyClass.i); // Compiles OK }  private static int i=100; 

Not sure why variable initialization do not need variable access using class name while SOP requires ?

like image 598
Kaild Avatar asked May 19 '13 13:05

Kaild


People also ask

Can we use static variable in static block?

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

Can we access static variable in instance block?

We cannot directly access the instance variables within a static method because a static method can only access static variables or static methods. An instance variable, as the name suggests is tied to an instance of a class.

How can we use static variable in static method in Java?

The static variables can be used only in the class scope where they are defined. The static variables in java can be declared like class members of the class like static int number, is the valid declaration of the static variable but static variables cannot be declared in any kind of method.

Can static block call static method in Java?

Static block call your method only once at time of class creation, If you want to call method at time of class creation you can call it. Static block is only way by which you can call your static methods at time of class creation.


1 Answers

This is because of the restrictions on the use of Fields during Initialization. In particular, the use of static fields inside a static initialization block before the line on which they are declared can only be on the left hand side of an expression (i.e. an assignment), unless they are fully qualified (in your case MyClass.i).

So for example: if you insert int j = i; right after i = 100; you would get the same error.

The obvious way to solve the issue is to declare static int i; before the static initialization block.

like image 54
assylias Avatar answered Oct 29 '22 03:10

assylias