javeine
Для чего нужны аргументы командной строки String args[] в методе main?
Метод main() указывает интерпретатору класс, с которого нужно начать выполнение программы. Однако в языке Java разрешено использовать несколько методов с названием main() даже в одном классе. Поэтому по-настоящему главный метод содержит аргументы командной строки (String[] args).
public class Testmain <
public static void main(String[] args) <
if(args.length > 0) // если через консоль были введены аргументы
System.out.println(args[0]); // то вывести на консоль первый элемент из массива
else < // иначе —
Testmain obj = new Testmain(); //создать объект
obj.main(); // и использовать обычный метод с названием main()
>
>
public static void main() < // это обычный метод с названием main()
System.out.println(«it’s usual main method without String[] args!»);
>
>
.

В командной строке консоли после команды java Testmain было введено три аргумента: 1 2 3. В программе строка System.out.println(args[0]); выводит на консоль первый аргумент массива args[0], в данном случае выведено 1.
Если же аргументы не были указаны через консоль, то выполняется блок оператора else, в котором вызывается обычный метод, но тоже названный main().
Дополнительная информация:
args в методе main() — это название массива String[] и оно может быть другим.
Command-Line Arguments
A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.
The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt , a user would enter:
When an application is launched, the runtime system passes the command-line arguments to the application's main method via an array of String s. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String : "friends.txt" .
Echoing Command-Line Arguments
The Echo example displays each of its command-line arguments on a line by itself:
The following example shows how a user might run Echo . User input is in italics.
Note that the application displays each word — Drink , Hot , and Java — on a line by itself. This is because the space character separates command-line arguments. To have Drink , Hot , and Java interpreted as a single argument, the user would join them by enclosing them within quotation marks.
Parsing Numeric Command-Line Arguments
If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as "34", to a numeric value. Here is a code snippet that converts a command-line argument to an int :
parseInt throws a NumberFormatException if the format of args[0] isn't valid. All of the Number classes — Integer , Float , Double , and so on — have parseXXX methods that convert a String representing a number to an object of their type.
String args java что это


Если все сделано верно, то в консоли отобразится текст: Write once, run anywhere. Переводится, как «Написано однажды, работает везде» — это девиз Java.
Если в коде есть какие-то проблемы, то выведется ошибка. Для ее устранения нужно еще раз внимательно сверить свой код с предложенным выше.