3

I see that length of an array is a keyword in java and that String has a method length().

How can a keyword return a numeric value, when it is not explicitly declared to do so?

Frakcool
  • 10,915
  • 9
  • 50
  • 89
  • You're right to observe that this is a bit "irregular". They do a bit of a tap-dance to explain it, but mainly it relates to the very early days of Java when it was only going to be used on set-top boxes. Some things got started off odd and they never straightened them up. – Hot Licks Apr 07 '14 at 18:26
  • 1
    length is not a keyword – dev2d Apr 07 '14 at 18:27
  • 1
    Yep, technically `length` is a field. Which begs the question: How can an array have a field? – Hot Licks Apr 07 '14 at 18:28
  • @HotLicks Probably because an array is an object. I guess that arrays use `length` because arrays are objects that are supposed to feel like primitives. – Justin Apr 07 '14 at 18:30
  • @Quincunx - So why doesn't `String` have a read-only `length` field? There's really no good argument one way or the other -- this is just the way they did it, and it got to be too late to change before there was time to do the change. – Hot Licks Apr 07 '14 at 18:54
  • @HotLicks My argument is that an array is supposed to feel like a primitive, while a `String` is supposed to feel like a method. At least that is how I feel when I write programs. Additionally, Java has a lot of backwards compatibility, so changing the array's `length` field to a method would destroy a large amount of the backwards compatibility. So yes, we sort of agree on this. I just have my own ways of thinking about things that the language's syntax encourages (in my mind) – Justin Apr 07 '14 at 18:57
  • 1
    @Quincunx - In other words, you've convinced yourself that it's correct. ;) – Hot Licks Apr 07 '14 at 18:59
  • (Also, if arrays have `length` and `String` has `length()`, then obviously an `ArrayList` has ...?) – Hot Licks Apr 07 '14 at 19:01
  • How can an array have a field? Because an array is an object, and objects can have fields. Why is Java inconsistent? Because Java is inconsistent. – David Conrad Apr 07 '14 at 19:12

1 Answers1

2

array has a public final int field length for array class

from jls-10.3

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

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438