Possible Duplicate:
Java - Array’s length property
String.length() vs Array.length
I'm currently in my AP Computer Science class in high school and I came across this in my reading.
From what I understand, .length()
is a method used for strings, but why isn't .length()
a method when applied on arrays? I understand that they're different objects, but why didn't Java just make another method for finding the length of arrays?
I appreciate any response I get. Thanks!
Note that array length in Java is a property, not a method.
Java String length() Method The length() method returns the length of a specified string.
ArrayList doesn't have length() method, the size() method of ArrayList provides the number of objects available in the collection. Array has length property which provides the length or capacity of the Array. It is the total space allocated during the initialization of the array.
The key difference between Java's length variable and Java's length() method is that the Java length variable describes the size of an array, while Java's length() method tells you how many characters a text String contains.
Since arrays are fixed length defined at the time they are instantiated length is a public final field on the class. There is no need to make it a method since there is no calculation to be done at run time.
See this section of the Java Spec for details: http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.7
Now, as for the design question of why they didn't provide an accessor method to obtain the value isn't specified. Perhaps this was done before any other convention was set and this is just a legacy thing. Only the language designers would know the "why" portion of their decision to do it this way.
Arrays are defined in the Java Language Specification #10.7. In particular:
The members of an array type are all of the following:
- The public final field length, which contains the number of components of the array. length may be positive or zero.
- [...]
I can't answer why this approach was chosen by the language designers.
Interestingly, it was already the case in the Oak specifications, which is the ancestor of Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With