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?
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.
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.
Unlike the String and ArrayList, Java arrays do not have a size() or length() method, only a length property.
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.
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...
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.
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