Java ‘length’ dilemma: String.length() vs Array.length
Summary
A very common mistake during the development time is .length or .length() for array and string. Okay, now we try to understand and remember it so that we can remember it easily.
For array, length is a property.
It is a property and we pre-define it, and we only once can initialize an array size so, it is actually a final value.
For string, length is a function.
We can not access a string’s length as property because it is not pre-defined like array, java needs to calculate the length for string… !!!
Deep Drive
Interestingly java string is backed by array implementation actually (byte array). In that case, Sun Microsystem could use array’s length for string. Besides in Java, String is immutable, so there is no chance of length modification(!). But what is the philosophy behind this length function?
Mainly for maintaining encapsulation philosophy,(hide direct access of length variable). Moreover, the String class implements CharSequence, and length() came from it (Historically, String API is older than CharSequence !).
String.length() => O(1) or O(n)?
Order O(1), because it just returns the underlying byte array’s length.
Is this good practice: for(int i = 0; i < string.length(); i++) ?
Yes, it is ok, if we consider modern compiler’s are smart enough and they optimize code and remove function call.
Function call has some extra overheads so, I do not prefer this coding style. It is better to save the length value in other variables in case of this type of iteration.