Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference fn(String... args) vs fn(String[] args)

Whats this syntax useful for :

    function(String... args) 

Is this same as writing

    function(String[] args)  

with difference only while invoking this method or is there any other feature involved with it ?

like image 975
Nrj Avatar asked Nov 19 '08 10:11

Nrj


People also ask

Is String args [] and String [] args same?

String args[] and String[] args are identical. In the sense that they do the same thing, Creating a string array called args. But to avoid confusion and enforce compatibility with all other Java codes you may encounter I'd recommend using the syntax (String[] args) when declaring arrays.

What does Strings [] args mean?

String[] args means an array of sequence of characters (Strings) that are passed to the "main" function. This happens when a program is executed. Example when you execute a Java program via the command line: java MyProgram This is just a test. Therefore, the array will store: ["This", "is", "just", "a", "test"]

Why do we use args [] in the main method?

When you run Java program, by right click on Java class with main method, it creates a Run Argument for that class. By the way, you can write your String args[] as String[] args as well, because both are valid way to declare String array in Java.

Why do you need String [] args?

Whenever you run a Java program with command prompt or want to give command line arguments, then “String[] args” is used. So basically it takes input from you via command lines. If you don't use command line arguments then it has no purpose to your code. Javac is used for compiling your source code.


1 Answers

The only difference between the two is the way you call the function. With String var args you can omit the array creation.

public static void main(String[] args) {     callMe1(new String[] {"a", "b", "c"});     callMe2("a", "b", "c");     // You can also do this     // callMe2(new String[] {"a", "b", "c"}); } public static void callMe1(String[] args) {     System.out.println(args.getClass() == String[].class);     for (String s : args) {         System.out.println(s);     } } public static void callMe2(String... args) {     System.out.println(args.getClass() == String[].class);     for (String s : args) {         System.out.println(s);     } } 
like image 96
bruno conde Avatar answered Sep 29 '22 18:09

bruno conde