I added the following code to a new class I created in Java:
public static void main(String[] arguments) {
I understand what public, static and void mean, but what does (String[] arguments) mean?
Your main() method can take input parameters of type String if your program is run through a console like
java YourClass arg1 arg2
Now, within main() if you iterate the String [] like
for (arg : arguments)
System.out.println(arg);
it should print
arg1
arg2
Demo :
public class AddTwoNumbers {
public static void main(String[] args) {
if(args.length == 2) {
try {
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
System.out.println("a + b = " + a + " + " + b + " = "+ (a + b));
} catch (NumberFormatException e) {
System.err.println("Invalid Input: Please enter numbers.");
}
} else {
System.err.println("Missing Input: Please enter TWO numbers.");
}
}
}
You can run this on your console as
java AddTwoNumbers 2 3
and it should print
a + b = 2 + 3 = 5
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