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.
Just change the place of
cokePricevariable.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.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.