Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!
}
like image 437
Mangat Rai Modi Avatar asked Nov 28 '13 10:11

Mangat Rai Modi


People also ask

What is complexity of String length in Java?

The complexity is O(1) Since String class have the length as a field .

What does method length () do in String class?

Java String length() Method The length() method returns the length of a specified string.

Is String length () O 1 in Java?

Either the String class keeps the string's length in a variable. In that case this variable is just returned by length() and you get constant complexity, that is O(1).

What is length and length () in Java?

The length() method returns the number of characters present in the string. length vs length() 1. The length variable is applicable to an array but not for string objects whereas the length() method is applicable for string objects but not for arrays.


1 Answers

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.

like image 164
Narendra Pathai Avatar answered Oct 12 '22 09:10

Narendra Pathai