Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

length in arrays and length() in String

Why is length a data field in when we talk about arrays and length() when we talk about String in Java? Means:

int a[10] = {1,2,3,4,5,6,7,8,9,10};
String str = "foo";
int a_len = a.length;
int str_len = str.length();

Why is length not a function in case of arrays or vice versa?

like image 541
Vaibhav Agarwal Avatar asked Oct 17 '12 17:10

Vaibhav Agarwal


People also ask

What is the difference between string length () and array length?

Array variables are mutable, that is once the size of these variables is declared it can be changed during the program or code, while String objects are immutable that means once declared they cannot be modified.

What is the difference between a length () and a length?

Java length vs length() explained. 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.

Do arrays use length ()?

Unlike the String and ArrayList, Java arrays do not have a size() or length() method, only a length property.

How do I get the length of a string array?

With the help of the length variable, we can obtain the size of the array. Examples: int size = arr[]. length; // length can be used // for int[], double[], String[] // to know the length of the arrays.


2 Answers

Simply: that's just the way it is, and the way it's always been.

It's specified in JLS section 10.7 that arrays have a public final length field. It could have been specified as a method instead, for consistency - but it just wasn't... equally String could have made an implementation decision to have a public final length field - but again, it happens not to be that way.

There are a few bits of inconsistency which have survived since 1.0 - obviously these things really can't be changed after release...

like image 136
Jon Skeet Avatar answered Sep 29 '22 12:09

Jon Skeet


String implements CharSequence and thus length needs to be a method in this case since interfaces can only specify methods.

Arrays don't need to implement any interface, so length is implemented as a public final field in this case to avoid extra method call overhead.

Edit:

As Hot Licks pointed out below, CharSequence didn't exist before Java 1.4. Although CharSequence obviously wasn't the driving reason behind this design choice (since it didn't exist), it would still make sense to choose this design with the idea that String might need to implement new interfaces in the future.

like image 39
DaoWen Avatar answered Sep 29 '22 10:09

DaoWen