8

Possible Duplicate:
Why is String.length() a method?
Java - Array's length property

Was there a specific design/performance reason as to why String has a method for length but Array has a variable length?

Community
  • 1
  • 1
Chander Shivdasani
  • 9,878
  • 20
  • 76
  • 107
  • 3
    Related: http://stackoverflow.com/questions/9297899/java-arrays-length-property – wkl Aug 22 '12 at 22:19
  • 1
    Also related http://stackoverflow.com/questions/8720220 – Steve Kuo Aug 22 '12 at 22:25
  • It's not a final public property because differing implementations exist -- indeed, there are indications that the current implementation may indeed be replaced by one without a special `length` field in the near future. – Louis Wasserman Aug 22 '12 at 22:28
  • If you have a CharSequence reference variable pointing to a String, you couldn't get the length of it if length was a field because fields aren't defined by interfaces. But arrays don't implement interfaces so length being a field is fine. – MeBigFatGuy Nov 22 '14 at 16:55

1 Answers1

8

There is no Array class in Java (other than in reflections). Arrays are "primitives" of a sort in Java and play by different rules from declared classes.

Certainly a length() method could have been defined on arrays, but the designers wanted to keep length as a property rather than a pseudo-method. (In part this may have made it easier for early Java implementations.) The reasons are somewhat buried in history.

(A better question is why Java couldn't decide whether to call the concept "length", "count", or "size" -- I always end up trying all three before I hit on the right one for an aggregating class.)

Hot Licks
  • 47,103
  • 17
  • 93
  • 151