Search code examples
javaclassprogram-entry-point

Java multiple Classes and multiple main methods, execute all main methods


Im new to Java and I just wrote some Code in which I used two classes with main methods. Id like to execute both main methods, one after another. Is there a possibility to execute both of them at once in a specified order?

imFirst.java

public class imFirst {
    public static void main(String[] args) {
        System.out.println("I want to be the first one executed!");
    }
}

imSecond.java

public class imSecond {
    public static void main(String[] args) {
        System.out.println("I want to be the second one executed!");
    }
}

these are in one package, executed via eclipse.


Solution

  • You can call imSecond's main from imFirst:

    public class imFirst {
        public static void main(String[] args) {
            System.out.println("I want to be the first one executed!");
            imSecond.main(args);
        }
    }
    

    Or can be the opposite:

    public class imSecond {
        public static void main(String[] args) {
            System.out.println("I want to be the second one executed!");
            imFirst.main(args);
        }
    }
    

    Do it depending of your needs. But don't do both things at the same time or you can get an endless loop of both methods calling each other.

    As a side note: use proper java naming conventions. Class names should be CamelCase.