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 ?
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.
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"]
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.
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With