Trent Boult
Trent Boult

Reputation: 117

Java programs don't necessarily start from main(), do they?

My instructor used to tell me that Java programs start from the main function. However, is this true?

I mean, if there are any global variables declared, they get allocated memory before the main() begins, right?

Upvotes: 1

Views: 75

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200236

Technically it is true that a Java program may be executed in entirety before the main method executes. Any program of the form

class X {
  public static void main(String[] args) {
      ... any code as long as it doesn't refer to args ...
  }
}

can be rewritten to

class X {
  static {
      ... the same code ...
  }
  public static void main(String[] args) {
  }
}

and have exactly the same behavior. Note that the main method is still required, but it will execute after all other code of the program.

Upvotes: 3

pvytykac
pvytykac

Reputation: 144

You can find more details about this in the documentation here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html

Short version:

  1. JVM is started and attempts to call the main method
  2. It finds out that the class is not loaded, so it tries to load the class
  3. All the super-classes need to be loaded as well
  4. Then it finds out that the class is not initialized so it initializes it (static variables are initialized here)
  5. It starts executing the main method

Upvotes: 2

Related Questions