Is it O(n) or O(1) (By saving length in a private variable during string allocation to the object).
if it is O(n), does it mean that the complexity of following code is
In Java any String is backed up by an final
array. So it is simple to just return the array length. So it is O(1)
complexity. And if you think in your code
for(int i=0; i
s.length()
is called for every iteration then you are not right. Modern compiler optimizes this type of call and changes s.length()
to constant number(i.e the length of the String
instance).