Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of

Program Executable Entry Points

In C or Java, the obvious place to begin looking for a place to start the program is the main method. However, this search can be easier said than done.

A simple text search, done with something like grep or a built-in Windows search tool, is going to find main all over the place, including inside comments and even inside other words (remain, domain, mainframe). You can get somewhat smarter using regular expressions, but in a large project you'll still end up eyeballing more code than you'd really like.

Most integrated development environments (IDEs) can provide a list of methods to examine. These tools parse the programs and show you main, the method, preferably the one that takes (int argc, char *argv[]) for C/C++ programs or (String[] args) in Java.

Java in particular can fool you; I've seen programmers spend many fruitless minutes trying to figure out why this program doesn't work:

class HelloWorld
{
  public static void main()
  {
    System.out.println("Hello, world");
  }
}

which produces the following helpful error message from Java:

java.lang.NoSuchMethodError: main
Exception in thread "main"

The answer, of course, is that it should be public static void main(String[] args).

The other pitfall of trying to find main is that many programs have multiple mains. Some classes come with main methods as a way to run a test on that class. From the name alone, it can't be distinguished from the program's "real" main. The comments may help:

/** Runs a test */
public static void main(String a[]) {
  JFrame f = new JFrame();
  f.getContentPane().add(new ThisComponent());
  f.pack();
  f.setVisible(true);
}

Except for the comment, this could well be the genuine main of the program. Your only other clue is that it's a bit brief. For example, it doesn't configure a menu. If the main doesn't create any graphics widgets at all, that's another clue that it's just a test (unless, of course, it's a server whose only interface is to set up an RMI listener, a CORBA class, or other such network-oriented protocol).

If your Java project has been helpful enough to provide a manifest, you can find the main class by looking at the manifest.mf file. The line Main-Class: identifies which class is the one that should actually be run. You might also try poking around in the .sh and .bat files associated with the project to see which classes they run.

Of course, not every project starts with a main. If the interface to your program is an applet, look for a class that subclasses JApplet or Applet.

  • + Share This
  • 🔖 Save To Your Account