Static
|
The main() Method
The
main()
method is a special static method that serves as the entry point for Java applications. It is declared as
static
because the
main()
method is called by the Java runtime before any objects are created. The
main()
method can call static
public static void main(String args[]) {
// body of method
}
An alternative, and
public static void main(String[] args) {
// body of method
}
The
main()
method must be declared in the class whose
The main() method can take command line arguments. These are included in the syntax to run the Java program and are passed to the main() method as a String array. For example, the following syntax would run the program MyProgram.class with two command line arguments named arg1 and arg2 ” java MyProgram arg1 arg2 The command line argument arg1 would be placed into args[0]. The command line argument arg2 would be placed into args[1] . Command line arguments are always passed to main() as String objects. If a command line argument is intended to be a number, you can convert it from a String to the desired primitive type. Command line argument delimiters are white space. If an argument has white space in it, surround it with double quotes. For example, the text "Bobby McGee" (with the double quotes) would be treated as a single command line argument. Example: Using Command Line Arguments in main()
The
main()
method of the
CommandLine
class calls the static
public class CommandLine {
public static void main(String args[]) {
// Convert the command line arguments from
// Strings to doubles.
double height = Double.parseDouble(args[0]);
double width = Double.parseDouble(args[1]);
// Call the hypotenuse method
System.out.println("hypotenuse is "+
StaticDemo.hypotenuse(height, width));
}
}
Output ” Your output will vary according to the command line arguments you provide. If you run this program by typing java CommandLine 3.0 4.0 you will get the output hypotenuse is 5.0. |