what is command line argument in java and how it is work

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

and what is .length in upper code.
is it function no it is not function
is it class no it is not a class
then what is .length plz help me

Recommended Answers

All 8 Replies

Length is number of values in array called args.

length is like an instance variable that arrays have. It contains the length (size) of the array. In this case it's telling you how many command line arguments there are

and since it isn't private, you don't need a get-method to retrieve it.

james cherrill you mean length is only like an instance variable but it is not actually an instance variable. am i write.
then actually what is it
and the use of loop in neessary for command line argument.

Arrays are objects, and length works just like a public final instance variable. The Language Spec says

10.7 Array Members
The members of an array type are all of the following:
• The public final field length, which contains the number of components of
the array. length may be positive or zero.
...

You don't need a loop, eg if you are expecting either one or two command line argument you could code:

public static void main(String []args){
  if (args.length < 1) ... // report an error and terminate
  ... args[0] ...  // use the first argument
  if (args.length == 2) ... args[1] ...  // use second argument

length() is actually a method inside of all Arrays. It returns how many values are stored inside of the Array.

The for loop is necessary in that example, however because it is an Array, you could simply use args[1] or some other number. It highly depends what you need it for.

NO!

length is a variable. There is NO length() method for arrays. Mahybe you are confusing it with String, which does have a length() method?

you can check that it is an variable, rather than a method, by testing this:

int a = myArray.length; // this will compile and work
int b = myArray.length(); // which will throw a compile time error, since length is not a method.
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.