Monday, May 20, 2024
HomeProgrammingCan we run a Java program without the main method

Can we run a Java program without the main method

Can we run a Java program without the main method?

The mainly method is executed when we execute a class in Java. For example, if we have a Main.java file with the following code:

public class Main {
    public static void main(String[] args) {
        System.out.println("Inside main");
    }
}

and if we run this program, it will print the string Inside head.

But if I do the mainly method,

public class Main {
    public void hello() {
        System.out.println("Inside main");
    }
}

An exception is thrown:

Error: Main method not found in class com.company.Main, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

To run a Java program without the main() method:

We can write a Java program without the main method with a static block only up to Java 1.5. A static block is written with the static keyword. This method is executed once the class file is loaded into memory. You need to write your code in the static block:

You can have more than one static block. These blocks are executed before the mainly method. The execution order is similar to the order in which they are added to the class. If you need to perform something before the mainly method is executed, you can add the code in a static block.

So the program below will work (up to Java 1.5):

public class Main {
    static {
        System.out.println("Inside main");
    }
}

For the later Java versions, we have no other way to run a program without the mainly method.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments

бнанс Створити акаунт on The Interview Process in Clark, Pampanga
Binance注册奖金 on Venus in Scorpio