Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't .length() a method for arrays in Java? [duplicate]

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!

like image 339
joejacobz Avatar asked Jan 27 '13 23:01

joejacobz


People also ask

Is array length a method in Java?

Note that array length in Java is a property, not a method.

What does length () do in Java?

Java String length() Method The length() method returns the length of a specified string.

What is the difference between length () and size () of ArrayList?

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.

What is difference between length and length () method in Java?

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.


2 Answers

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.

like image 191
Michael Avatar answered Oct 04 '22 21:10

Michael


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.

like image 32
assylias Avatar answered Oct 04 '22 20:10

assylias