+ 4
What happens before main()?
Just curious if methods before main compile and execute before reaching main method or afterwards and is it diffrent with with certain keywords like static, public ect? Thanks
3 Antworten
+ 6
Compilation to bytecode will occur prior to any Java code being executed. This is a separate process from the execution of the code and is usually done independently. The order in which the code is compiled is highly abstracted away from what the typical Java coder/programmer/developer will ever need to know. If this is the information you wish to learn then your best bet is to do some extensive research into the Java compiler and the JVM etc.
When it comes to execution of Java bytecode, static members, fields, blocks etc, will be initialized, instantiated, run, etc prior to the main method being ran. Static members need to take precedence to the main method during execution. If you were to utilize a static member within the main method of your program and the static member had not previously been initialized, you would most likely receive a error such as a null pointer exception.
Take the code below for example:
public class Program
{
static {System.out.println("Static Block Running");}
public static void main(String[] args) {
System.out.println("Main Method Running");
}
}
Here the static block will run prior to the main method and the output will be as follows:
Static Block Running
Main Method Running
+ 28
i like it ☺
//thank u both for a good question as well as a nice answer 😃
+ 6
wow thanks @Chaotic ✅✅✅✅✅✅✅😀