r/javaTIL • u/Ameridrone • Aug 29 '13
You should know that "args[]" means that you can send arguments to the program via the command line and reference the position like "args[0]". Examples inside.
I have always been told that the whole:
public static void main(String args[])
line was literally always required, however until recently I didn't know the "args" part, and to be honest...it seems like many don't.
So here is the deal: args are what are sent the program, and you can send them command line.
You will need to of course compile your .java file. Personally, I enjoy doing it the old fashioned way (makes me feel smarter than I am), and I use the command line.
If you are unfamiliar with how this is done, all you do is navigate to where ever the .java file is, and type:
javac filename.java
ANYWHO, here is an example program which uses args:
public class addition
{
public static void main(String args[])
{
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
System.out.println(num1 + num2);
}
}
In my example, once compiled, you can change directory to where the .class file is, an execute the program.
The example I have provided takes exactly two arguments.
java addition 1 2
This will return the number 3!
5
u/[deleted] Aug 29 '13
You can even replace String[] args with String... args so that you can call your main method internally using varargs
1
u/Xaotik-NG Feb 03 '14
Might just be me nitpicking here, but it's always a good idea to provide defaults and account for any number/type of arguments if you plan on using args: