Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, for a string x, what is the runtime cost of s.length()? Is it O(1) or O(n)?

Tags:

java

string

I've been told that code such as:

for (int i = 0; i < x.length(); i++) {     // blah } 

is actually O(n^2) because of the repeated calls to x.length(). Instead I should use:

int l = x.length(); for (int i = 0; i < l; i++) {     // blah } 

Is this true? Is string length stored as a private integer attribute of the String class? Or does String.length() really walk the whole string just to determine its length?

like image 483
someguy Avatar asked Oct 31 '08 19:10

someguy


People also ask

What is length and length () in Java?

The key difference between Java's length variable and Java's length() method is that the Java length variable describes the size of an array, while Java's length() method tells you how many characters a text String contains.

What does length () do in Java?

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

Is length () a string in Java?

The Java String length() method is a method that is applicable for string objects. length() method returns the number of characters present in the string. The length() method is suitable for string objects but not for arrays. The length() method can also be used for StringBuilder and StringBuffer classes.

What is the time complexity of string length?

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


2 Answers

No, the length of a java string is O(1) because java's string class stores the length as a field.

The advice you've received is true of C, amongst other languages, but not java. C's strlen walks the char array looking for the end-of-string character. Joel's talked about it on the podcast, but in the context of C.

like image 100
sblundy Avatar answered Oct 01 '22 17:10

sblundy


Contrary to what has been said so far, there is no guarantee that String.length() is a constant time operation in the number of characters contained in the string. Neither the javadocs for the String class nor the Java Language Specification require String.length to be a constant time operation.

However, in Sun's implementation String.length() is a constant time operation. Ultimately, it's hard to imagine why any implementation would have a non-constant time implementation for this method.

like image 22
Alexander Avatar answered Oct 01 '22 17:10

Alexander