Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic beginners in Java: what does 'arguments' mean in Java

Tags:

java

arguments

iv'e been trying to learn basic java programming for the last 2 days, and I encountered an issue i can't figgure while viewing the following code:

class DayCounter {
    public static void main(String[] arguments) {

        int yearIn = 2008;
        int monthIn = 1;
        if (arguments.length > 0)
            monthIn = Integer.parseInt(arguments[0]);
        if (arguments.length > 1)
            yearIn = Integer.parseInt(arguments[1]);
        System.out.println(monthIn + "/" + yearIn + " has "
            + countDays(monthIn, yearIn) + " days.");
    }
}

I can't understand the line if (arguments.length > 0) what does arguments mean? Where did the value come from?

like image 372
user3921 Avatar asked Oct 08 '12 12:10

user3921


2 Answers

I can't understand the line "if (arguments.length > 0) what does "arguments" mean? where did it value came from?

It came from the method declaration:

public static void main(String[] arguments) {

That declares a parameter called arguments. For a normal method call, the caller specifies the argument, and that becomes the initial value of the parameter. For example:

int foo(int x) {
    System.out.println(x);
}
...
foo(10);

Here, 10 is the argument to the method, so it's the initial value for the x parameter.

Now a public static void method called main in Java is an entry point - so when you run:

java MyClass x y z

the JVM calls your main method with an array containing the command line arguments - here, it would be an array of length 3, with values "x", "y" and "z".

For more details, see the relevant bits of the Java tutorial:

  • Passing information to a method or constructor
  • Command-line arguments
like image 105
Jon Skeet Avatar answered Sep 22 '22 23:09

Jon Skeet


arguments are the command line options given to your java program when it runs. They are stored in an array so calling arguments.length gives the number of command line inputs to your program.

They are passed in like this on execution

java program argument1, argument2, argument3

In this case arguments.length would return 3 as there are 3 command line arguments.

like image 28
Daniel Gratzer Avatar answered Sep 20 '22 23:09

Daniel Gratzer