One of the options is to use static function as initializer to static variable. Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method.
What you need is a static keyword. One of the options is to use static function as initializer to static variable.
class Main {
public static int value = printHello();
public static int printHello() {
System.out.println("Hello");
return 0;
}
public static void main(String[] args) {
System.out.println("Main started");
}
}
value is a static variable so initialized before main function execution. This program prints:
Hello
Main started
Moreover, you can even simplify this by calling printHello() even without variable initialization like in the following:
static {
printHello();
}