Explain the main () method in Java in detail _java

Source: Internet
Author: User

Objective

The main functions in Java are more familiar to us, it is believed that every person who has studied the Java language can skillfully write the entry function of the program, but for why the main function is written, what each of these keywords means, may not be easy for everyone to answer. I also encountered this problem in the study, through the online search materials, and add their own practice finally have a little experience, dare not keep, write to share with you.

The main () method in Java

The Java Virtual machine finds the running program that needs to be started through the main method, and checks whether the class that contains the main function is loaded by the Java virtual machine. If there is no mount, the class is loaded and all related other classes are loaded. So when the program is running, the first method to execute is the main() method. In general, if you want to run a method of a class, you must first instantiate an object of the class and then run the method by using the " object name. Method Name () ", but since main is the entry for the program, there is no instantiation of the object. Therefore, the main method is declared static so that the method can be invoked directly through the " class name. Method Name () ".

Before looking at the main () method in Java, look at one of the simplest Java application HelloWorld, and I'll illustrate the mystery of the methods in the Java class by this example main() , and the code for the program is as follows:

 
the main () method in/** * Java is detailed * 
* public 
class HelloWorld {public 
 static void Main (String args[]) { 
 System.out.println ("Hello world!"); 
 } 

first, say class:

The HelloWorld class has a main() method that shows that this is a Java application that starts the program directly from the JVM.
Since it is a class, Java allows classes to not be constrained by the public keyword, and of course the definition of a class can only be limited to public or unrestricted keywords (default).

Second, again main () method

The main() declaration of this method is: public static void main(String args[]) . It has to be defined, and this is the Java specification.

Why this definition is related to the operation of the JVM.

When there is a method in a class main() , executing the command "Java class name" starts the virtual machine to execute the main method in the class.

Because the JVM is running this Java application, it first calls the main method, which does not instantiate the object of the class, but is called directly by the class name and therefore needs to be restricted to public static.

For the main method in Java, the JVM has a limit and cannot have a return value, so the return value type is void.

The main method also has an input parameter, the type is string[], this is also the Java specification, the main() method must have an incoming parameter, the class fine must String[] , as for the string array name, this can set itself, according to the custom, this string array name general and Sun In the Java specification paradigm, the Mian parameter names are consistent and named args.

Therefore, the main() method definition must be: " public static void main(String 字符串数组参数名[]) ".

Three, main () method can throw Exception

Therefore main() , an exception can be thrown in a method, and an main() exception can be declared on a method.

For example, the following is the correct wording:

public class Testmain {public 
 static void Main (string[] args) throws Exception { 
  System.out.println ("hahaha"); C9/>throw New Exception (""); 
 } 
}
Run result: Ha ha
ha 
Exception in thread "main" java.lang.Exception: at 
 maintest. Testmain.main (testmain.java:11) at 
 sun.reflect.NativeMethodAccessorImpl.invoke0 (Native method) 
 at Sun.reflect.NativeMethodAccessorImpl.invoke (nativemethodaccessorimpl.java:39) at 
 Sun.reflect.DelegatingMethodAccessorImpl.invoke (delegatingmethodaccessorimpl.java:25) at 
 Java.lang.reflect.Method.invoke (method.java:585) at 
 Com.intellij.rt.execution.application.AppMain.main ( APPMAIN.JAVA:90) 

Process finished with exit code 1

The function of the string parameter array in the main () method

main()A string parameter array in a method receives command-line input parameters, separated by a space between the arguments of the command line.

Here's an example to see how to initialize and use this array.

/**
* Print input parameters in Main method * 
/public class Testmain {public 
 static void Main (String args[]) { 
 System.out.println ("Print the input parameters in the Main Method!") "); 
 for (int i=0;i<args.length;i++) { 
  System.out.println (args[i]);}} 

Executing methods and running results

D:\study\basetest\src>javac Testmain.java 

D:\study\basetest\src>java testmain 1 2 3 
Print the input parameters in the Main method! 
1 
2 

Give a different version of HelloWorld

/** 
* Abnormal version of the HelloWorld. Hehe * * * public 
class HelloWorld2 { 
 static { 
 System.out.println ("Hello Wordld! "); 
 } 
 public static void Main (String args[]) { 
 system.exit (0); 
 } 
}

This main() method executes the contents of the sentence " System.exit(0); ", the purpose is to let the program end normally. That "helloworld! "Where it is printed, the secret is printed in static, because the contents of the static code block are invoked before the main call.

Vi. examples

The virtual machine starts by invoking the method main of a specified class, passing to main a string array parameter so that the specified class is loaded, linking the other types used by the class, and initializing them. For example, for programs:

public class HelloApp {public
 static void Main (string[] args) {
 System.out.println ("Hello world!");
 for (int i = 0; i < args.length i++) {
  System.out.println (args);
 }
}}

After compiling, type in command line mode: Java HelloApp run virtual machine

The Java Virtual machine will be started by calling HelloApp's method main, which is passed to main with an array of three strings "run", "virtual", "machine". Now we outline the steps that virtual machines may take to perform helloapp.

Started trying to execute the main method of class HelloApp and found that the class was not loaded, meaning that the virtual machine does not currently contain a binary representation of the class, so the virtual machine uses ClassLoader to try to find such binary representation. If this process fails, an exception is thrown. Once a class is loaded and before the main method is invoked, the class HelloApp must be linked to and initialized with other types. Links include three stages: inspection, preparation, and parsing. The validation examines the symbols and semantics of the loaded main class, prepares to create static fields for classes or interfaces, and initializes these fields to standard defaults, parsing the symbolic reference of the main class to the other classes or interfaces, which is optional in this step. The initialization of a class is the execution of an initialization constructor for a static initialization function and a static domain declared in a class. A class has to be initialized before it initializes its parent class.

The whole process is as follows:

Summarize

The main method, as a special specification, is very different from the ordinary one, and has many limitations, so it is necessary to learn the knowledge of the JVM. is a major obstacle to learning in Java. The above is a small series for everyone to organize the main principle and use of the summary, I hope that we can help, if you have questions you can message exchange.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.