Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal forward Reference java issue

Tags:

java

Could anyone explain what is wrong with this code:

    public class Base {


    static {
        i = 1;
        System.out.println("[Base]after static init block i=" + i);// LINE 1
        System.out.println("*************************************");
        System.out.println();
    }
    static int i;



    public static void main(String[] args) {
        System.out.println(Base.i);
    }
}

If I comment LINE 1 - everything is OK and Base.main method prints "1". If LINE 1 - is not commented, got compile time error: "illegal forward reference". So, as i understand in static init block I can set value for i, but not read. Could anyone explain why?

like image 326
Timofei Avatar asked Jan 31 '13 11:01

Timofei


People also ask

Why Illegal forward reference Java?

In the second statement, it declares variable 'b' and tries to find where is 'c'. But, it is not declared yet. Therefore, it gives illegal forward reference error. Illegal forward reference is nothing but you are referring to something in advance that does not exist yet.

Are forward references allowed in Java?

Java allows very flexible forward references. A method may refer to a variable or another method of its class, regardless of where in the current class the variable or method is defined.

What is reference error in Java?

The ReferenceError object represents an error when a variable that doesn't exist (or hasn't yet been initialized) in the current scope is referenced.

What is forward reference in Java?

Core Java bootcamp program with Hands on practice Forward references are commands that refer to methods, variables, or classes that don't exist in any code we have typed in JShell. As code entered and evaluated sequentially in JShell, these forward references have temporarily unresolved.


2 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 Base.i).

So for example: if you insert int j = i; right after i = 1; 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 191
assylias Avatar answered Sep 21 '22 09:09

assylias


"Illegal forward reference" means that you are trying to use a variable before it is defined.

The behavior you observe is a symptom of a javac bug(see this bug report). The problem appears to be fixed in newer versions of the compiler, e.g. OpenJDK 7.

have a look at

Illegal forward reference error for static final fields

like image 45
Massimiliano Peluso Avatar answered Sep 22 '22 09:09

Massimiliano Peluso