How to Run Java Code that Straddles Two Separate Files

By Barry Burd

From Eclipse’s point of view, a project that contains two Java source files is no big deal. You create two classes in the same project, and then you choose Run→Run As→Java Application. Everything works the way you expect it to work.

The only time things become tricky is when you have two main methods in the one project. As you experiment with your code, you can easily add classes with additional main methods. You may also create a large application with several starting points.

When a project has more than one main method, Eclipse may prompt you and ask which class’s main method you want to run. But sometimes Eclipse doesn’t prompt you. Instead, Eclipse arbitrarily picks one of the main methods and ignores all the others. This can be very confusing. You add a println call to the wrong main method, and nothing appears in the Console view. Hey, what gives?

You can fix the problem by following these steps:

  1. Expand the project’s branch in the Package Explorer.

  2. Expand the src folder within the project’s branch.

  3. Expand the (default package) branch within the src branch.

    The (default package) branch files.

  4. (In Windows) Right-click file whose main method you want to run. (On a Mac) Control-click file whose main method you want to run.

  5. In the resulting context menu, choose Run As→Java Application.

You cannot run a project that has no main method.