Home >Java >javaTutorial >What is the use of args in java
args in Java is a string array containing command line arguments, used to configure the program, pass data and script automation. Get the args through the main method and use a loop to process each argument, as in the example above to sum the numbers.
The purpose of args in Java
args
in Java is a string array , which contains command line parameters, which are parameters passed in when running a Java program.
Usage scenarios
args
Usually used in the following scenarios:
args
Can be used to write scripts that automate program operations, such as batch processing of files or running a specific test suite. Get args
The Java program can get args
through the main
method:
<code class="java">public static void main(String[] args) { // 使用 args 数组获取命令行参数 }</code>
Example
The following is a simple example that calculates the sum of all numbers on the command line:
<code class="java">public static void main(String[] args) { int sum = 0; for (String arg : args) { try { int num = Integer.parseInt(arg); sum += num; } catch (NumberFormatException e) { // 忽略非数字参数 } } System.out.println("数字之和:" + sum); }</code>
Run the program:
<code>java MyProgram 10 20 30 40</code>
Output:
<code>数字之和:100</code>
The above is the detailed content of What is the use of args in java. For more information, please follow other related articles on the PHP Chinese website!