What is the time complexity of String.length() in Java?

java, time-complexity

Solution

It is `O(1)` as the length is already known to `String` instance.

From JDK 1.6 it is visible.

public int length() {
    return count;
}

Update

It is important to understand why they can cache the value of `count` and keep using same value for `count`. The reason lies in a great decision they took when designing `String`, its Immutability.

Problem

Is it O(n) or O(1) (by saving the 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 O(n^2)? ``` for(int i=0; i<s.length()-1;i++){ //some code here! } ```

Original source