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?
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:
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.
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