4

Possible Duplicate:
Why is String.length() a method?

If I want to know the length of an array I will have to type the following:

array.length

Therefore, it is a variable in which is written the length of the array called 'array'.

On Strings the same thing will look like this:

string.length()

Therefore, it's a method that returns the length of the 'string' variable.

But why did they choose to make those two different, while it basically does the same thing... Is this because of efficiency or why else?

Thank you in advance.

Community
  • 1
  • 1
brgr
  • 318
  • 3
  • 16
  • The first may be regarded as a property of the object array, but the second is a method accessing the object string. If I'm wrong, I'm waiting for correction. – SaidbakR Dec 10 '12 at 21:53
  • 1
    "Why is this so" questions are typically not appropriate for this forum. Try (programmers.se](http://programmers.stackexchange.com/) – Miserable Variable Dec 10 '12 at 21:54
  • It's basically history/tradition. Theoretically, arrays could use `length()` or String could use `length` (which is conceptually a read-only instance field), but they got started off differently. There is some slight advantage to having array `length` being a pseudo-field in terms of code interpretation/generation, but the advantage, while present at the inception of Java, is largely gone with modern implementations. – Hot Licks Dec 10 '12 at 21:56
  • @JBNizet -- `length` is a public field of arrays, yet no one can change it. It's one odd special case -- a wart on the architecture. – Hot Licks Dec 10 '12 at 21:57
  • I forgot about the final keyword for a moment, don't know why :-/ – JB Nizet Dec 10 '12 at 21:59
  • Add to that size() for collections. length, length(), size() ... arrggh! – xagyg Dec 10 '12 at 22:28

1 Answers1

1

good question.

arrays are fixed in size and therefore have a public final length field.

strings are implementing the CharSequence interface that have the length() function that needs to be implemented.

Julien May
  • 2,011
  • 15
  • 18