Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does (String[] arguments) mean? [duplicate]

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?

like image 743
Tony Smith Avatar asked Mar 18 '26 10:03

Tony Smith


1 Answers

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
like image 144
Ravi K Thapliyal Avatar answered Mar 21 '26 01:03

Ravi K Thapliyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!