25

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 ?

3
  • did you mean to show an error in both blocks? Commented May 19, 2013 at 13:47
  • 1
    @Bohemian I think this is a copy/paste fail. The second block shouldn't show errors. Commented May 19, 2013 at 13:49
  • see also stackoverflow.com/questions/15820302/… Commented May 19, 2013 at 18:25

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 Cool. I didn't know that, nor have I encountered it. Also I can't believe it's taken me this long to figure out your name :/
It actually is a coincidence but nice one anyway!
@assylias Sorry for any inconvenience, I tested it locally only in that way, the >>same error<< can occur.
Yes agreed, for the same reason.
0

this is because compilers doing static code analysis, for example the live variable analysis (backward analyze). It calculates for each program point whether the variable will be read before the next write.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.