+ 6
[DUPLICATE] Why we write String[] args in java
in public static void main(String[]args)
9 Answers
+ 1
Lets a java file named Program.java
public class Program{
public static void main(String[] args){
if(args.length > 0){
for(String arg: args){
System.out.println(arg);
}
}else{
System.out.println("There is no arguments!");
}
}
}
Compile from terminal :
javac Program.java
Then run from terminal:
java Program
It will print : There is no arguments!
The run with arguments:
java Program 1 a hello
It will print:
1
a
hello
In soloLearn you cant add commandline arguments, in any IDE you can pass it by the run configuration.
Try it your local machine.
I hope you understood now.
+ 6
Thanks Szabo and antriksh
+ 5
not understood
+ 5
Please tell in detail and with better example
+ 2
String [] arguments is a java array of Stringobjects. 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.
+ 1
1) args contains the supplied command line argument as an array of type string.
Ex :-
public class Test {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++) { System.out.println(args[i]); } }
2) If you run your program as
java [.class file name] one two
then args will contain ["one", "two"]
0
Because you can pass outer arguments.
foe example if run from command line:
Java Program.class 1 a hello
Inside in main the args = {"1","a","hello"}
0
There is a video if you like it better:
https://www.youtube.com/watch?v=-CbBayOZrEw
0
we write it because of command line arguments