0

hi, this is a simple program but i have no idea what the args.length is for.

class PrintArgs {

  public static void main (String[] args) {
    for (int i = 0; i < args.length; i++) { 
      System.out.println(args[i]);
    }
    
  }
  
}

i added a few more lines(below) to the code to try to make sense of it but i keep getting "There are 0(zero) command line arguments"

here's the modified version

class PrintArgs 
{

  public static void main (String[] args) 
  {

     for (int i = 0; i < args.length; i++) 
     { 
      System.out.println(args[i]);
    }
    
     System.out.print("There are ");
    System.out.print(args.length); 
    System.out.print(" command line arguments");
    System.out.println();
  }
  
}

Thanks

5
Contributors
5
Replies
28
Views
10 Years
Discussion Span
Last Post by masijade
1

args.length is the length of the array of commandline arguments.
If you don't pass any arguments that length will be 0 ;)

Votes + Comments
This was helpful. I couldn't figure out what a commandline argument was. Thanks a ton.
0

As mentioned before, the args.length value is the number of items in the args array.

If you pass no command-line arguments, you will always get "There are 0 command line arguments".

But try running the program like this: java PrintArgs hello my name is mikki2 The words after java PrintArgs are called command line arguments because they are arguments passed to your program from the command line.

0

Thanks guys!...and as usual...lightning fast answers! (just took a while for me to reply is all)

0

An instance variable of Class Array (which is the class behind all arrays). It is an int.

Edit: And, as noted, it represents the length of the array, and since arrays are 0-indexed, the last index of the array is length - 1, of course.

Edited by masijade: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.