Java Tutorial/Language/Main — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:06, 1 июня 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

  1. A special method called main provides the entry point to an application.
  2. An application can have many classes and only one of the classes needs to have the method main.
  3. 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()");
    }
  }
}