Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Length of an array and String

 
Vallabhaneni Suresh Kumar
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why we are using arrayname.length to find the length of an array and string.length() for a String? Why we are not using length() method for an array?
 
Ulf Dittmer
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because an array is not strictly speaking an object (i.e. it does not extend Object), so you can't call methods on it, and it shouldn't look like you can.
 
Mani Ram
Ranch Hand
Posts: 1140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An array is an object. Try this


But, why you refer it as a property (length), instead of a method (length()) - no clue. Let me think about it.
[ July 22, 2005: Message edited by: Mani Ram ]
 
Steve Simon Joseph Fernandez
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I may be wrong on this, but this is what I think:

IMHO, String.length() has to be a function and not a public final variable because String is implemented by java code itself. So, it doesn't know the length of the string until it creates it, and thus it can't provide it as a final variable. On the other hand, arrays for primitive types are implemented via an external platform-dependent dll, which returns the specified object. Thus, java code will know the length of an array when it gets it back from the dll, and thus can provide a public final property for the same.

P. S. Don't kill me if I'm wrong ;-)

_steve.
 
Niki Nono
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The array.length is a variable which has the size of the array.
the string.length() is a function which calculates the length of the string.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Niki Nono:

the string.length() is a function which calculates the length of the string.


If you take a look at the implementation, it just returns the value of the private "count" field. The count field is only assigned in constructors.

BUT - for the count field to be public, it would have been vital to also make it final. That's no problem for arrays, which can only be constructed in very specific ways. For String it might constrain the class' design too much to be a good idea.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic