Can assign a static variable but cannot print it out in a static initializer

111 Views Asked by At

I am able to assign value to a static variable but am not able to print it out in the same static block.

If I move the static variable above the static block, then all works well. Now I am failing to follow the sequence of execution of the code. The code was run in java.

class ExampleStatic{

static {
    cokePrice=12; 
    System.out.println("Coke Price is: R"+cokePrice);   
}
static int cokePrice;

public static void main(String[] args) {    
}
}

I expected the output to print the Coke Price is: R12. However an error says: Cannot reference a field before it is defined.

3

There are 3 best solutions below

2
Y.Kakdas On

Just change the place of cokePrice variable.

static int cokePrice;

static {
cokePrice=12; 
System.out.println("Coke Price is: R"+cokePrice);   
}

And the situation does not come just for the System.out.print, the issue is about restrictions in java. It allows to use variable in static method without initialize it unless you are using it as right hand assignment. If you use it as left hand assignment, it is safe.

static int cokePrice;

static {
cokePrice=12; 
int x = cokePrice;   
}

static int cokePrice;

This, also will give error because we use it as right hand assigning. To be safe, initialize your variable before your static block, or do not use it as right hand assignment. I hope this clarifies your thoughts.

0
vijay On

This is because "Illegal forward reference"

Means that you are trying to use a variable before it is defined.

Try this

 static int cokePrice;
    static {
        cokePrice=12;
        System.out.println("Coke Price is: R"+cokePrice);
    }
0
Prakash On

You need to declare variable inside static block as local variable. some thing like this

`class A {
    static {
        int c = 10;
        System.out.print(c);
    }
}`