I'm just beginning to write programs in Java. What does the following Java code mean?
public static void main(String[] args)
What is String[] args
?
When would you use these args
?
Source code and/or examples are preferred over abstract explanations
5. String[] args. It stores Java command-line arguments and is an array of type java.
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.
public static void main(String[] args) Java main method is the entry point of any java program. Its syntax is always public static void main(String[] args) . You can only change the name of String array argument, for example you can change args to myStringArgs .
String [] arguments is a java array of String objects. This means that the main function expects an array of Strings. This array of strings typically holds all command line parameter arguments passed in when the program is run from the command line.
In Java args
contains the supplied command-line arguments as an array of String
objects.
In other words, if you run your program in your terminal as :
C:/ java MyProgram one two
then args
will contain ["one", "two"]
.
If you wanted to output the contents of args
, you can just loop through them like this...
public class ArgumentExample { public static void main(String[] args) { for(int i = 0; i < args.length; i++) { System.out.println(args[i]); } } }
The program will print in the terminal:
C:/ java MyProgram one two one two C:/
Those are for command-line arguments in Java.
In other words, if you run
java MyProgram one two
Then args
contains:
[ "one", "two" ]
public static void main(String [] args) { String one = args[0]; //=="one" String two = args[1]; //=="two" }
The reason for this is to configure your application to run a particular way or provide it with some piece of information it needs.
If you are new to Java, I highly recommend reading through the official Oracle's Java™ Tutorials.
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