Multiple Main Functions

Ben picture Ben · Jul 19, 2012 · Viewed 25.9k times · Source

I'm a bit new at this so bear with me. I'm currently learning C# and Java and one of their similarities is that the main function needs to be encapsulated within a class. For example

public class HelloWorld {
    public static void main(String[] args) {
        // Some Code
    }
}

Now I understand that main is often the "entry point" when you run the program. So basically, your program will start executing wherever the main function is. But I believe in both languages you can have multiple main functions within multiple classes. So when I compile a project with multiple main functions, where is the "entry point"? How does the compiler know where to start?

Answer

Code-Apprentice picture Code-Apprentice · Jul 19, 2012

In Java, the computer determines the "entry point" when you actually execute the program, not when you compile. For example, from the command-line

java MyClass

searches for main() in MyClass. All other main() functions are ignored.

If you are using an IDE, then you can set which class contains the main() function that you want to use.