Java Tutorial/Language/Main
Версия от 17:44, 31 мая 2010; (обсуждение)
Содержание
Display all command-line arguments.
class CommandLine {
public static void main(String args[]) {
for (int i = 0; i < args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
New parameter for main method
public class Main {
public static void main(String... args) {
for (String arg : args) {
System.out.println(arg);
}
}
}
The Method main
- A special method called main provides the entry point to an application.
- An application can have many classes and only one of the classes needs to have the method main.
- This method allows the class containing it to be invoked.
The signature of the method main is as follows.
public class MainClass {
public static void main(String[] args) {
}
}
All arguments must be passed as strings. For instance, to pass two arguments, "1" and "mode" when running the Test class, you type this:
java Test 1 mode
Throw Exception through main method
public class MainClass {
public static void main(String[] args) throws Throwable {
try {
throw new Throwable();
} catch (Exception e) {
System.err.println("Caught in main()");
}
}
}