Can you run a code before executing the main method In Java?
In Java, you cannot run code before the main
method in the traditional sense of executing a method. However, you can achieve similar behavior using static initializers or static blocks. These blocks of code are executed when the class is loaded, before the main
method is called.
Here’s an example to illustrate this:
public class Example {
// Static block
static {
System.out.println("Static block executed before main method.");
// You can put any initialization code here
}
public static void main(String[] args) {
System.out.println("Main method executed.");
}
}
Example
is loaded into memory, which happens before the main
method is invoked.Static block executed before main method.
Main method executed.
main
method runs.