Java Tutorial/Language/Main

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

Display all command-line arguments.

   <source lang="java">

class CommandLine {

 public static void main(String args[]) {
   for (int i = 0; i < args.length; i++)
     System.out.println("args[" + i + "]: " + args[i]);
 }

}</source>





New parameter for main method

   <source lang="java">

public class Main {

 public static void main(String... args) {
   for (String arg : args) {
     System.out.println(arg);
   }
 }

}</source>





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.



   <source lang="java">

public class MainClass {

 public static void main(String[] args) {
 }

}</source>



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

   <source lang="java">

public class MainClass {

 public static void main(String[] args) throws Throwable {
   try {
     throw new Throwable();
   } catch (Exception e) {
     System.err.println("Caught in main()");
   }
 }

}</source>