There was an error in this gadget

Thursday, June 19, 2008

main()

There are two basic types of Java programs: applets and applications.* Applets run through a browser or a special program called AppletViewer. Applications are stand-alone programs that run on the same system they're stored on, like most traditional programs. Since there's lots of information elsewhere on applets, we'll concern ourselves mostly with applications.

Every application has a special method called main(). The main() method marks the starting point in the program for the Java Virtual Machine. Here's a short example program:

public class Hello{
public static void main(String arg[]){
System.out.println("Hello");
}
}

When this program is compiled using javac then run with the command
>java Hello
the JVM loads Hello.class and looks in it for the main() method, then starts executing the code inside main()'s code block.

Now, you'll notice there's a bunch of other stuff with main():
public static void main(String arg[]){

Because of how Java works, that stuff has to be there in a Java application. You can't just put "main(){" on the line by itself. The other stuff has a purpose, though it all looks very confusing, and certainly it looks like a lot of extra junk in a short program.

public allows the method to be accessed from outside the class (and its package--we'll get into that later.) If you leave out public, the JVM can't access main() since it's not available outside of Hello.

static says that this is the one and only main() method for this entire class (or program). You can't have multiple main()s for a class. If you leave static out, you'll get an error.

void says that main() doesn't pass back any data. Since the JVM wouldn't know what to do with any data, since it's not set up to accept data from main(), main() has to be of type void, which is to say that it's a method that doesn't pass any data back to the caller. If you leave this out main() won't have a data type, and all methods have to have a data type, even if it's void.

Inside main()'s parentheses is String arg[]. This is a way for the program to accept data from the host system when it's started. It's required that main() be able to accept data from the system when starting. And the data must be in the form of an array of Strings (or a variable-length list of Strings as of Java 5, but that's something we'll save for later.) The name "arg" can be whatever you want to make it. It's just a name I've given the array. It could just as well be:
public static void main(String fred[]){

I'd just have to be sure to use fred whenever I wanted to access the information that the system has passed to my application when it started, instead of arg.

Finally, after the parentheses, comes the open curly brace { that marks the start of main()'s code block.




* There are other types as well, but I'm limiting my discussion to Java SE/client side stuff for now.
StumbleUpon