javeine
Метод 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[] и оно может быть другим.
public class Testmain2 public static void main(String[] lalala)
if(lalala.length > 0) // если через консоль были введены аргументы
System.out.println(lalala[0]); // то вывести на консоль первый элемент из массива
else < // иначе —
Testmain2 obj = new Testmain2(); // создать объект
obj.main(); // и использовать обычный метод с названием main()
>
>
public static void main() < // это обычный метод с названием main()
System.out.println(«it’s usual main method without String[] lalala!»);
>
>
.
В чем различия между массивами String [] args и String. args?
Запись вида methodName(T. args) называется varargs (Variable Arguments)
Удобство в том, что можно передавать сразу аргументы и не создавать массив и количество аргументом может быть 0 или N. Пример:
public static void vargs(final String. strings) < System.out.println(strings); >public static void arrs(final String[] strings) < System.out.println(strings); >public static void main(final String. args) < vargs(); // ok vargs("1", "2"); // ok arrs(); // compilation error arrs(new String[] ); // ok >
Есть пара моментов: методы с varargs нельзя перегружать и varargs должен быть последним аргументом
public static void manyParams(final String. strings, final Integer number) < // compilation error >public static void manyParams(final Integer number, final String. strings) < // ok >
Ответ написан более трёх лет назад
Комментировать
Нравится 4 Комментировать
What is String args[ ] in Java?

String args[] in java is an array of type java.lang.String class that stores java command line arguments. Here, the name of the String array is args (short form for arguments), however it is not necessary to name it args always, we can name it anything of our choice, but most of the programmers prefer to name it args.
We can write String args[] as String[] args as well, because both are valid way to declare String array in Java.
From Java 5 onwards, we can use variable arguments in main() method instead of String args[] . This means that the following declaration of main() method is also valid in Java : public static void main(String. args) , and we can access this variable argument as normal array in Java.
Why is String. args[] in Java Needed?
Varargs or Variable Arguments in Java was introduced as a language feature in J2SE 5.0. This feature allows the user to pass an arbitary number of values of the declared date type to the method as parameters (including no parameters) and these values will be available inside the method as an array. While in previous versions of Java, a method to take multiple values required the user to create an array and put those values into the array before invoking the method, but the new introduces varargs feature automates and hides this process.
The dots or periods( . ) are known as ELLIPSIS , which we usually use intentionally to omit a word, or a whole section from a text without altering its original meaning. The dots are used having no gap in between them.
The three periods( . ) indicate that the argument may be passed as an array or as a sequence of arguments. Therefore String… args is an array of parameters of type String, whereas String is a single parameter. A String[] will also fulfill the same purpose but the main point here is that String… args provides more readability to the user. It also provides an option that we can pass multiple arrays of String rather than a single one using String[] .
Example to Modify our Program to Print Content of String args[] in Java
When we run a Java program from command prompt, we can pass some input to our Java program. Those inputs are stored in this String args array. For example if we modify our program to print content of String args[] , as shown below:
The following Java Program demonstrates the working of String[] args in the main() method:
How to Run:
Compile the above program using the javac Test.java command and run the compiled Test file using the following command:
Output :
Explanation:
In the above example, we have passed three arguments separated by white space during execution using java command. If we want to combine multiple words, which has some white space in between, then we can enclose them in double quotes. If we run our program again with following command:
Output:
Conclusion
- string args[] in java is an array of type java.lang.String class that stores java command line arguments.
- Variable argument or varargs in Java allows us to write more flexible methods which can accept as many arguments as we need
- The three periods(. ) in String… args[] indicate that the argument may be passed as an array or as a sequence of arguments.
- (String… args) is an array of parameters of type String, whereas String[] is a single parameter. String[] can full fill the same purpose but just (String… args) provides more readability and easiness to use.
Oh! Whats this ‘…’ in public static void main(String … args) in Java?
Java programmers have a very close connection to writing the main function as public static void main(String[] args). Those who have been working with it for some time have got into depth and know what that statement in the parenthesis means.
To those who don’t know it yet can also guess if you got your basics right. Its a String array and it names as ‘args’(short form for argument). Well, that wasn’t a hard nut to crack. But what if I ask you to guess what does ‘String … args’ could mean, what could all the possibilities be that you could think of?
Rather than directly coming over the exact meaning, let me tell you something about — ELLIPSIS.
ELLIPSIS is a series of dots or period(‘…’) that are used in almost all languages (No! Not the programming languages, the general languages- English, German and so on) which we usually use intentionally to omit a word, sentence, or a whole section from a text without altering its original meaning. The dots are used having no gap in between them. An example is English, we say: It is not cold… it is freezing cold.
The same is used in programming languages and also in mathematics. Example: In mathematics, it is used as 1+2+3+…+100 and we know it at a glance that the dots represent rest of the missing numbers . Looks a bit familiar, isn’t it? Ellipsis is used in numerous programming languages starting from Pascal, C to Python and to C++, Go and Java. In C, C++, and Java, it is used as a Variadic function, a function of an indefinite number of arguments.
Varargs or Variadic function in Java was introduced as a language feature in J2SE 5.0. The argument of the method can be declared as a variable arity parameter or simply varargs method. This allows one to pass a variable number of values of the declared type to the method as parameters(including no parameters) and these values will be available inside the method as an array.
void printNumbers(int. numbers) <
//numbers represents varargs
for (int num : numbers) System.out.println(num);
>
>
// Calling varargs method
printNumbers(1,2,3,4,5);
The output would be the numbers displayed as one per each line.
But why was it needed?
In Java’s past releases, a method to take an arbitrary number of values required to create an array and put the values into the array prior to invoking the method. It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process. Furthermore, it is upward compatible with preexisting APIs. The three periods indicate that the argument may be passed as an array or as a sequence of arguments.
Hence (String… args) is an array of parameters of type String, whereas String[] is a single parameter. String[] can full fill the same purpose but just (String… args)provides more readability and easiness to use. It also provides an option that we can pass multiple arrays of String rather than a single one using String[]. It can be used when the programmer wishes to you Varargs as per the program requirements.
If you found the blog useful, show your love by .
