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! }
This O(1)is because the length is already known to the instance String.
O(1)
String
From JDK 1.6 it is visible.
public int length() { return count; }
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
final
s.length() , . s.length() (.. String).
s.length()
Difficulty O(1)Since the class Stringhas a length of like field. This is not O (n ^ 2).
field
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.