0

Can somebody explain me why below program produce 10 and 0 ?. I would expected 10 and 10;

public final class Testing {
    static int j = function1();
    static int i = 10;

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

    public static int function1() {
    return i;
    }

}
Cataclysm
  • 6,575
  • 16
  • 67
  • 121

1 Answers1

2

static variables are initialized in the order they appear in the source code of the class. Therefore when j is initialized, i is still 0 by default, so function1 returns 0 and j is initialized to 0.

After j is initialized to 0, i is initialized to 10, and your main prints 10 and 0.

JLS 12.4.2 :

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

Eran
  • 374,785
  • 51
  • 663
  • 734
  • Thanks a lot ... clear and perfect solution for me. – Cataclysm Nov 23 '15 at 06:43
  • 1
    replace the order of the two lines: static int i = 10; static int j = function1(); This is because the memory of i (integer) is initialised with 0 before you make it 10. – W. Steve Nov 23 '15 at 06:49