args.length and command line arguments

Wang Pei The Dancer picture Wang Pei The Dancer · Aug 26, 2013 · Viewed 66.5k times · Source

I got confused with how to use args.length, I have coded something here:

public static void main(String[] args) {
    int[] a = new int[args.length];

    for (int i = 0; i < args.length; i++) {
        System.out.print(a[i]);
    }
}

The printout is 0 no matter what value I put in command line arguments, I think I probably confused args.length with the args[0], could someone explain? Thank you.

Answer

Maroun picture Maroun · Aug 26, 2013

int array is initialized to zero (all members will be zero) by default, see 4.12.5. Initial Values of Variables:

Each class variable, instance variable, or array component is initialized with a default value when it is created ...

For type int, the default value is zero.

You're printing the value of the array, hence you're getting 0.

Did you try to do this?

for (int i = 0; i < args.length; i++) {
     System.out.print(args[i]);
}

args contains the command line arguments that are passed to the program.
args.length is the length of the arguments. For example if you run:

java myJavaProgram first second

args.length will be 2 and it'll contain ["first", "second"].

And the length of the array args is automatically set to 2 (number of your parameters), so there is no need to set the length of args.