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?
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
lengthfield. It could have been specified as a method instead, for consistency – but it just wasn’t… equallyStringcould have made an implementation decision to have a public finallengthfield – 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…