Java's main

Source: Internet
Author: User

three basic ways in which users pass parameters to the system in Java

Main method

In Java, the main () method is the entry method for a Java application, that is, when the program is running, the first method to execute is the main () method, which differs greatly from other methods, such as the name of the method must be main, and the method must be public For a static void type, the method must receive a string array of arguments, and so on. The declaration of this main () method is: public static void Main (String args[]). This must be defined, which is the Java specification. Why this is defined is related to the operation of the JVM. When there is a main () method in a class, executing the command "Java class name" will start the virtual machine to execute the main method in that class. Since the JVM is running this Java application, the main method is called first, and the object of the class is not instantiated, 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, type string[], this is the Java specification, the main () method must have a parameter, the class must be string[], as for the name of the string array, this can be set by itself, according to the habit, The name of this string array is generally consistent with the Mian parameter name in the Sun Java specification paradigm, named args. Therefore, the main () method definition must be: "public static void main (string string array parameter name [])". The function of the string parameter array in the main () method is to receive command line input parameters, separated by a space between the parameters of the command line. public class HelloWorld2 {    static {        System.out.println ("Hello wordld!");    }    public static void Main (String args[]) {        system.exit (0);}    } The main () method executes the phrase "system.exit (0);", to allow the program to end normally. That "helloworld! "Where is it printed, the secret is printed in static, because the contents of the static code block are called before the main call.

The first is passed through the main method

     Public class Mainargs       {          publicstaticvoid  main (string[] args)           {              System.out.println ( args.length);                for (String Str:args) {                  System.out.println (str);}}      }  

The string (one or more spaces separated by a space) following the run of the Java program will assign one or more of these strings to the args array. When a string contains spaces, you need to enclose the entire string with "".

The second use of the scanner class

User input using the Scanner class: You can enter a user-specified data type
Scanner uses the delimiter mode to break its input into markup, which by default matches whitespace. You can then use a different next method to convert the resulting token to a different type of value.

1     ImportJava.util.Scanner; 2     ImportJava.io.File; 3      Public classscannerkeyboardtest4     {  5          Public Static voidMain (string[] args)throwsException6         {  7             //Readfilecon (); 8             //test2 (); 9       Ten             //specify type by keyboard input OneScanner scan =NewScanner (system.in);  ALong L =Scan.nextlong ();  -System.out.println ("L is" +l);  -         }   the         //reads any data input to return a string -          Public Static voidtest1 () { -Scanner scan =NewScanner (system.in);  -        +             //Use the ENTER key as the delimiter by default using the SPACEBAR tab to enter as a split payment.  -             //scan.usedelimiter ("\ n");  +              while(Scan.hasnext ()) { ASystem.out.println ("Next is" +Scan.next ());  at             }          -         }   -        -         //read input of Long data returns long -          Public Static voidtest2 () { -Scanner scan =NewScanner (system.in);  in             //when a non-long value is entered, the loop is rolled out -              while(Scan.hasnextlong ()) {//Block Type to                 //System.out.println ("Have over Scan.nextlong () begin ...");  +System.out.println ("Next is" +Scan.nextlong ());  -                 //System.out.println ("Scan.nextlong () over have begin ...");  the             }   *         }   $         //read the contents of the file and print to the consolePanax Notoginseng          Public Static voidReadfilecon ()throwsException -         {   theScanner scan =NewScanner (NewFile ("Scannerkeyboardtest.java"));  +System.out.println ("Filecontent is:");  A              while(Scan.hasnextline ()) { the System.out.println (Scan.nextline ());  +             }   -         }   $}

The third is to use the BufferedReader class to read the user's input: only the string class is returned

1     ImportJava.io.BufferedReader; 2     ImportJava.io.InputStreamReader; 3     classbufferreaderkeyboardtest4     {  5          Public Static voidMain (string[] args)throwsException6         {  7BufferedReader br =NewBufferedReader (NewInputStreamReader (system.in)); 8String in =NULL; 9              while(in = Br.readline ())! =NULL){  TenSYSTEM.OUT.PRINTLN ("User entered:" +In );  One             }          A         }   -}

System.in is a bit stream, in order to convert to a character stream, you can use InputStreamReader for character conversion, and then use BufferedReader for it to add buffering capabilities. For example:
BufferedReader reader = new BufferedReader (new InputStreamReader (system.in));

1. The Java.io.BufferedReader and Java.io.BufferedWriter classes each have a 8192-character buffer. When BufferedReader reads a text file, it tries to read the character data from the file and place it in the buffer, and then reads from the buffer before using the Read () method. If the buffer data is not enough to be read from the file again, when using BufferedWriter, the data written is not first exported to the destination, but is first stored in the buffer. If the data in the buffer is full, the destination is written out one at a time.

2. When the user input is read directly from the standard input stream system.in, the user enters one character at a time and system.in reads one character. To be able to read the input of a row of users at a time, BufferedReader is used to buffer the characters entered by the user. The ReadLine () method passes the entire line of strings again when it reads the newline character of the consumer.

3. System.in is a bit stream, in order to convert to a character stream, you can use InputStreamReader for character conversion, and then use BufferedReader for it to add buffering capabilities. For example:
BufferedReader reader = new BufferedReader (new InputStreamReader (system.in));

1      PackageYsu.hxy; 2     ImportJava.util.*; 3     ImportJava.io.*; 4       5      Public classBufferedreaderwriterdemo6     {  7          Public Static voidMain (string[] args)8         {  9             Try  Ten             {   One                 //buffered system.in input stream A                 //system.in is a bit stream that can be converted to a character stream by InputStreamReader -BufferedReader Bufreader =NewBufferedReader (NewInputStreamReader (system.in));  -                 //Buffer FileWriter theBufferedWriter Bufwriter =NewBufferedWriter (NewFileWriter (args[0]));  -        -String input =NULL;  -        +                 //One write action per read line -                  while(! (input = Bufreader.readline ()). Equals ("Quit"))   +                 {   A bufwriter.write (input);  at                     //The NewLine () method writes a newline character that is dependent on the operating system, depending on the execution environment's current OS to determine the output type of newline character - Bufwriter.newline ();  -                 }   - Bufreader.close ();  - Bufwriter.close ();  -             }   in             Catch(arrayindexoutofboundsexception e) -             {   toSystem.out.println ("No File Specified");  +             }   -             Catch(IOException e) the             {   * E.printstacktrace ();  $             }  Panax Notoginseng         }   -}

Compile and run the above program

D:\hxy>java Ysu.hxy.BufferedReaderWriterDemo Test2.txt
111111111111
222222222222
Quit

Creates a file test2.txt in the directory and writes the content that you just entered.

Java's main

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.