In Java, for a string x, what is the runtime cost of s.length()? Is it O(1) or O(n)?

No, the length of a java string is O(1) because java’s string class stores the length as a field.

The advice you’ve received is true of C, amongst other languages, but not java. C’s strlen walks the char array looking for the end-of-string character. Joel’s talked about it on the podcast, but in the context of C.

Leave a Comment