What is the complexity of the length () function in a Java String class?

This is O (n) or O (1) (By storing the length in a private variable when distributing the string for the object).

if it is O (n), does this mean that the complexity of the following code is O (n ^ 2)?

for(int i=0; i<s.length()-1;i++){
    //some code here!
}
+4
source share
4 answers

This O(1)is because the length is already known to the instance String.

From JDK 1.6 it is visible.

public int length() {
    return count;
}
+8
source

In Java, any String is created by an array final. Therefore, just simply returning the length of the array. So the complexity O(1). And if you think in your code

for(int i=0; i<s.length()-1;i++){
    //some code here!
}

s.length() , . s.length() (.. String).

+1

Difficulty O(1)Since the class Stringhas a length of like field. This is not O (n ^ 2).

0
source

String internally supports array , and the length of the array is a property of the array object, therefore O (1) is a simple read of the property.

0
source

All Articles