-1

here i have written java program

    public class Main {
    static int i=2000;

    public static void main(String[] args) {
        System.out.print("value of j inside main "+j);

    }

    static {
        m1();
        System.out.print("value of i inside static block "+i);
    }


    static void m1() {
        System.out.print("inside static method");
        System.out.print("value of j inside static block "+j);
    }
    static int j =3000;




   }

inside static block, the value of i is printed as 2000, but value of j can't be referred in static block? and value of j printing in m1() method is 0, but j is initialized then why is it printing 0? why j cant be referred in static and it is referred in m1() which is first called by static block? and inside main, value of j is printing as 3000? so can anyone tell me what is wrong i am understanding here?

Anuj Patel
  • 39
  • 1
  • 5

2 Answers2

0

Here is the output from your current code:

inside static method value of j inside static block 0
value of i inside static block 2000
value of j inside main 3000

Static blocks in a Java class are evaluated in the order in which they appear. This means that when the static block making the m1() method call executes, j has not yet been assigned a value yet, so its value is reported as zero. On the other hand, i has already been assigned the value 2000, so it reports the value you expect.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

This is "Illegal forward reference" which means that you are trying to use a variable before it is defined. So you can move static int j =3000; before static block.

Vikas
  • 6,868
  • 4
  • 27
  • 41
  • But i am referring j before defining in m1(), then how's it possible? I can't refer in static block but can refer in m1() method – Anuj Patel Dec 29 '19 at 07:29
  • @AnujPatel https://stackoverflow.com/questions/12448465/in-what-order-are-static-blocks-and-static-variables-in-a-class-executed – Vikas Dec 29 '19 at 12:34