Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

A detailed explanation of String in the Java main method


May 30, 2021 Article blog



Every student who studies Java should have written the following piece of code.
public class Hello{
	public static void main(String[] args) {
		System.out.println("Hello,World!");
	}
}

In the Java language, it is specified that the entry function is a main() method that has an argument of the String type, but in many cases, many people do not use this argument and do not care why they should write it.

So what exactly is the argument of this string array type?

In fact, it is very simple, the main() method in the string array type parameters are the parameters of the java command, the java command way to run the main() method, the java command parameters into the Java main() method of the string array parameters.

We can verify this by:

  • 1, first write a Hello .java file, the contents of the document is as follows:
public class Hello{
	public static void main(String[] args) {
		System.out.println("==============args start============");
		for(int i = 0; i < args.length; i++) {
			System.out.println(args[i]);
		}
		System.out.println("==============args end============");
	}
}
  • 2. Open the cmd command prompt under the path of Hello .java file, run javac Hello .java command compile the file, which will get a Hello .class bytecode file under the corresponding file path.
  • 3, using the java Hello command to run Hello .class file, we will get the following results:
     A detailed explanation of String in the Java main method1
  • 4. This time, we add some parameters after the java command, which we can define ourselves. For example: java Hello a b c d, we'll get the following results:
  •  A detailed explanation of String in the Java main method2
It is precisely because of this extensibility of the Java main() method that each developer can implement some different functions by defining some parameters of the Java command himself.

Where SpringBoot's startup class actually uses this feature, the SpringApplication.run() method has an overloaded method, the first of which is the bytecode object of the class that annotates the @SpringBootApplication annotation, and the second argument, the string array parameter of the main() method.

SpringBoot can implement different application configurations in different environments by means of this string array parameter and java command parameters.

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

Recommended lessons:

Java: 23-day zero base fully started

Java Development Example: Tank Wars Game