0
public class testing {
    static testing tmp = new testing();

    testing() {
        System.out.println("You are good");
    }

    public static void main(String... str) {

    }
}

In the above code 'You are good' is printed. But I want to know why this happened as constructor is non static method and static variables execute before not static methods.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
KSan
  • 1
  • 1

2 Answers2

0

The static variables initialize when class loads for the first time. In your case the static variable is referring to the constructor of the same class so the cunstructor is called. Which then prints the statement System.out.println("You are good"); .
Similar question is asked here

The statement will not print if:

// 1. Non-static declaration
testing tmp = new testing();

// 2. Initialization skipped - no call to constructor
testing tmp2 = null; //new testing();
Prashant Zombade
  • 482
  • 3
  • 15
0

The declaration of the static variable tmp uses the constructor to initialize a new instance of testing. It doesn't matter that the constructor is technically a non-static (instance) method if it gets called inside the declaration of a static variable.

More precisely, the static variables of a class are initialized at some point during loading the class definition. This is completely independent of any calls to static or instance method later on in the code.

Etienne Ott
  • 656
  • 5
  • 14