-1

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.

SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
Tapiwa
  • 1
  • 1

3 Answers3

1

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.

Y.Kakdas
  • 833
  • 7
  • 17
  • Thanks, this has helped. However, may you please (if possible) explain why I was able to assign cokePrice before defining it and yet could not print it out. – Tapiwa Feb 13 '19 at 09:34
  • I edit the post for you,hope this helps. – Y.Kakdas Feb 13 '19 at 10:19
0

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);
    }
vijay
  • 75
  • 1
  • 9
0

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);
    }
}`
Prakash
  • 21
  • 4