Java Reference
In-Depth Information
methods are all we can call. This static method then typically creates the first object. The return
type is void , as this method does not return a value.
The parameter is a String array. This allows users to pass in additional arguments. In our
example, the value of the args parameter will be an array of length zero. The command line
starting the program can, however, define arguments:
java Game 2 Fred
Every word after the class name in this command line will be read as a separate String and
be passed into the main method as an element in the string array. In this case, the args array
would contain two elements, which are the strings "2" and "Fred" . Command-line parameters
are not very often used with Java.
The body of the main method can theoretically contain any statements you like. Good style,
however, dictates that the length of the main method should be kept to a minimum. Specifically,
it should not contain anything that is part of the application logic.
Typically, the main method should do exactly what you did interactively to start the same ap-
plication in BlueJ. If, for instance, you created an object of class Game and invoked a method
named start to start an application, you should add the following main method to the Game
public static void main(String[] args)
Game game = new Game();
Now, executing the main method will mimic your interactive invocation of the game.
Java projects are usually stored each in a separate directory. All classes for a project are placed
inside this directory. When you execute the command to start Java and execute your applica-
tion, make sure that the project directory is the active directory in your command terminal. This
ensures that the classes will be found.
If the specified class cannot be found, the Java virtual machine will generate an error message
similar to this one:
Exception in thread "main" java.lang.NoClassDefFoundError: Game
If you see a message like this, make sure that you have typed the class name correctly
and that the current directory actually contains this class. The class is stored in a file with
the suffix .class . The code for class Game , for example, is stored in a file named Game.
class .
If the class is found but does not contain a main method (or the main method does not have the
right signature), you will see a message similar to this one:
Exception in thread "main" java.lang.NoSuchMethodError: main
In that case, make sure that the class you want to execute has a correct main method.
Search WWH ::

Custom Search