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

Recommended Answers

All 5 Replies

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

commented: This was helpful. I couldn't figure out what a commandline argument was. Thanks a ton. +0
Member Avatar for Dukane

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.

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

it is right that args.length is length of cmd line arguments, args is array but length is not a fn.so what it is..

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.