The Java Main method

Source: Internet
Author: User

1. Question: Why is the Java Main method public static void main (string[] args)???

Serial number Scene Compile Run Explain
1 Public change to private protected or remove Normal Main Method not Public only when Main method is not on the public level. JVM visible, so you need to use Public Retouching
2 Remove Static Exception in thread "main" Java.lang.NoSuchMethodError:main if you want to make Main method as a program entry, you do not have to first create the class instance but call directly, so the method needs to use Static Retouching
3 Modifying the return value type The JVM is already at the bottom of the Java program, and the return value of the method it calls is nowhere to go, so the main method does not need a return value, so use the void modifier
4 modifying parameter types or adding multiple parameters The main method needs to receive the arguments passed in from the command line (separated by spaces), andthe Java specification uses a string array as the unique input parameter of the main method, and the parameter name can be not args, If the parameter is not worn, the array is Empty and not NULL
5 Modify Method Name contain Main the class of the method is Java Application, JVM only Identify Main as a program entry, you can only use Main as the method name
6 Add Throw Exception Normal The main method can throw an exception
7 Public and static interchange Locations Normal  

2. Problem: Main method as the entrance of the program

1  Public classMain2 {3     Static4     {5System.out.println ("123");6System.exit (0);7     }8 9      Public Static voidMain (string[] args)Ten     { OneSystem.out.println ("456");  A     } -}

Run Result: 123

When the JVM executes, it loads the class first, then executes the inner static block, and then calls the main method.

The static block print "123" in the previous example is forced to exit the program, and there is no chance to execute the main method.

The Java Main method

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.