Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "String args[]"? parameter in main method Java

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

like image 663
freddiefujiwara Avatar asked May 21 '09 00:05

freddiefujiwara


People also ask

What are the String [] args for in the main method?

5. String[] args. It stores Java command-line arguments and is an array of type java.

Why is String [] args used in 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.

What is String args [] in static void main String args []) for?

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 .

What does String [] mean in Java?

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.


2 Answers

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:/ 
like image 160
Dan Lew Avatar answered Sep 27 '22 03:09

Dan Lew


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.

like image 37
mR_fr0g Avatar answered Sep 26 '22 03:09

mR_fr0g