SanQA
SanQA

Reputation: 233

Printing static variable without class name leads to an error

public class ClearingDoubtsAboutStatic {

    static
    {
        System.out.println("Static Block1 Output: "+ClearingDoubtsAboutStatic.statVar);  //------Line 5
        statVar=20;  //-----Line 6
        System.out.println("Static Block1 Output: "+ClearingDoubtsAboutStatic.statVar); //------Line 7
        System.out.println("Static Block1 Output: "+statVar); //---Line 8

    }

    static int statVar=30;

    public static void main(String[] args) {

    }
}

What in my mind was that the line 7 and 8 will give the same output, but it is not the case.

My Question

what I don't understand is when we are able to initialize the static variable without the class name at line 6 but why we are not able to print it without the class name at line 8?

Upvotes: 3

Views: 633

Answers (3)

Mershel
Mershel

Reputation: 552

Hmmm i'm not sure about that but i will share with you my guess. Initialization starts first for everything that is static in Class (in defined order). So your static{...} is will be initialized at first, then statVar will receive its value. First printing should show 0 as this is default int value. It works because your are referencing it by Class name and that is how static variables should be referenced. There is one static variable for Class, not for object. When you are trying to reference it without class name, your are treating it like just some field in your class and you shouldn't try to reference those before they are defined. So compiler is not allowing to do so.

Upvotes: 0

Hearen
Hearen

Reputation: 7828

I not quite sure about your case but in my IntelliJ when I try your code, I got this:

Error:(9, 55) java: illegal forward reference

enter image description here

Upvotes: 0

Bsquare ℬℬ
Bsquare ℬℬ

Reputation: 4487

The 2 rules you copy/paste are wrong, you should only consider:

Static declaration and static block initialization are considered in the order they appear in the source file

Thus, you can fix your issue, changing the order of the declaration, and your static initialization block:

static int statVar=30;

static
{
    System.out.println("Static Block1 Output: "+ statVar);  //------Line 5
    statVar=20;  //-----Line 6
    System.out.println("Static Block1 Output: "+ statVar); //------Line 7
    System.out.println("Static Block1 Output: "+statVar); //---Line 8

}

Upvotes: 1

Related Questions