0

If I do args.length(); it is showing compilation error where as args.length is working fine.

but if it is not command line argument for eg. String str = "hello"; in this str.length is not working but str.length() is working fine.

please help!

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
shiwchiz
  • 43
  • 7
  • 1
    [length vs length() in java](http://stackoverflow.com/questions/1965500/length-and-length-in-java) – SatyaTNV Jan 26 '16 at 16:33
  • 1
    `.length()` for strings, `.length` for arrays. – Mohammed Aouf Zouag Jan 26 '16 at 16:33
  • It is often useful to include the compilation error in your post. I recommend that any new programmer take the tie to read the message of an exception when it is encountered as it will not only help when requesting advice, but will certainly aid you in identifying the cause of the exception. – OYRM Jan 26 '16 at 16:49

4 Answers4

5

Assuming you refer to the args parameter of a main method, that's because arrays do not provide a length() method like Strings, but a length public property, returning int.

See docs here.

Mena
  • 47,782
  • 11
  • 87
  • 106
1

String as an object has a built in method called length()

Array as an object does not have a built in method length(), but it has a property called length

OPK
  • 4,120
  • 6
  • 36
  • 66
0

The parameter arg of the main method is an Array.

Arrays have a public property length unlike Collections or Strings that have length() method

Wael Sakhri
  • 397
  • 1
  • 8
  • actually started learning java today only. so u means String args [] is an array of strings and length is a method for array? – shiwchiz Jan 26 '16 at 16:38
  • It not a method but an instance variable which is `public` and `final`. – Aniket Thakur Jan 26 '16 at 16:39
  • No, Arrays like `String [] args` don't have a `length()` method they have a **public property** where they store length. We acces public property like this : `args.length`. Java have another enhanced type of arrays called Collections like List ant Set they have a `length()` **method** like Strings – Wael Sakhri Jan 26 '16 at 16:42
  • @AniketThakur would you please elaborate? – shiwchiz Jan 26 '16 at 16:43
0

The public final field length, which contains the number of components of the array. length may be positive or zero.

There is no length() method. Documentation.

String class has a method called length() (Docs)

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289