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.

Answer from sblundy on Stack Overflow
🌐
Coderanch
coderanch.com › t › 472418 › java › string-length
O(n) of string.length() (Java in General forum at Coderanch)
What is the time complexity of string.length() function. Please explain the reason as well.
🌐
Stackademic
blog.stackademic.com › optimise-your-string-algorithms-in-java-ce88b8152311
Optimise your String Algorithms in Java | by Taosif Jamal | Stackademic
November 6, 2024 - Time Complexity: O(n) As mentioned before, strings are immutable in Java. Hence for creating a substring of length n, a new string instance needs to be created. Under the hood, java is actually creating a char array of length n and copying elements ...
🌐
Codeforces
codeforces.com › blog › entry › 21633
String length complexity... - Codeforces
String length complexity... ... Server time: Jan/08/2026 23:08:28 (g1).
🌐
Codekru
codekru.com › home › java string length() method
Java String length() method - Codekru
June 19, 2022 - Length of the string is: 7 · Yes, it’s that easy, and we don’t want to complicate it much. Now, let’s see some other scenarios. The time complexity of the length() function is O(1) as the String class has length as the field and returns the same when the length() function is used.
🌐
DEV Community
dev.to › taosif7 › optimise-your-string-algorithms-in-java-17ef
Optimise your String Algorithms in Java - DEV Community
September 10, 2022 - Strings are immutable in Java. Example: Lets say you concatenate "abc + "def" Under the hood, Java is performing these operations: • Construct copy of "abc" with additional length; • Copy "d" to new array • Construct copy of "abcd" • Copy "e" to new array • Construct copy of "abcde" • Copy "f" to new array So O(m) called n times, thus time complexity is O(mn)
🌐
GitHub
github.com › rootusercop › Learning-Java › blob › master › Time Complexity of predefined methods in JAVA
Learning-Java/Time Complexity of predefined methods in JAVA at master · rootusercop/Learning-Java
http://stackoverflow.com/questions/25514062/what-is-the-time-complexity-of-java-stringbuilder-substring-method-if-it-is-l ... It was O(1) in older versions of Java - as Jon stated, it just created a new String with the same underlying char[], ... However, this has actually changed started with Java 7 update 6. The char[] sharing was eliminated, and the offset and length fields were removed.
Author   rootusercop
Find elsewhere
Top answer
1 of 1
2

As told by OP, the problem and its the solution come from Elements of Programming Interviews in Java by Adnan Aziz, Tsung-Hsien Lee, and Amit Prakash.

Here is the excerpt of the book that analyzes the time-complexity of the solution.

The number of vertices is the number d of words in the dictionary. The number of edges is, in the worst-case, $O(d^2)$. The time complexity is that of BFS, namely $O(d + d^2) = O(d^2)$. If the string length $n$ is less than $d$ then the maximum number of edges out of a vertex is $O(n)$, implying an $O(nd)$ bound.

The above analysis in the book is correct. Please note "word" and "string" are used interchangeably here.

Here is OP's analysis, with the only modification that I use $d$ to denote the number of words so as to be consistent with the book.

The second loop is a constant (right?), it doesn't change with the size of $d$, so I don't think that is a part of the calculation for the run time.

OP's analysis is not wrong, either, if we assume that the length of the strings in the dictionary is bounded by a constant. This assumption is not unreasonable since it conforms to our ordinary experience about words in a normal dictionary. In fact, OP's analysis has been included in the book as well! It is the very last statement of the excerpt above.

Is there a logical inconsistency between the bounds $O(d^2)$ and $O(nd)$? No, since they apply to different situations with different assumptions. For example, in the worst case where every string differ in exactly one character with every other string, if we let $d$ go to infinity, then the maximal string length $n$ will goes to infinity as well. That is, "The second loop" does "change with the size of $d$"! Those strings are very unlikely to be words in our ordinary dictionary because of their huge lengths, of course.

In fact, in all cases, $d \leq 26n$. So $O(d^2)$ implies $O(nd)$.

🌐
Soumitra Saha's Blog
ssblogs.hashnode.dev › strings-in-java
String in Java String methods in Java String A-Z in Java
December 15, 2022 - In general, the time complexity ranges from O(1) for operations that only involve a constant number of operations, to O(n) for operations that involve iterating over the entire string.
🌐
Reddit
reddit.com › r/learnjava › what is the time complexity of this algorithm?
r/learnjava on Reddit: What is the time complexity of this algorithm?
February 21, 2021 -

Hi, I'm working on an exercise problem in my class; the problem asked me to create an algorithm to find the "maximum consecutive increasingly ordered substring" of an inputted string. Basically, it wants me to find the longest substring in a string where the letters are in alphabetical order.

I managed to implement the algorithm, but I'm not sure what the time complexity of it is.

public static String maxConsecutiveOrderedSubstring(String str)
{
    String subStr = "";
		
    for (int i = 0; i < str.length() - 2; i++)
    {
	// Read in the letter at the index
        String test = "" + str.charAt(i);
			
	// Read the following letters
	for (int j = i + 1; j < str.length(); j++)
	{
	    // If the next letter is before the current letter, break the loop
	    if (str.charAt(j - 1) + 1 > str.charAt(j))
                break;
	    test += str.charAt(j);
	}

	// If the substring just tested is longer than the one currently stored,
	// replace the currently stored string.
	if (test.length() > subStr.length())
            subStr = test;
			
        // Move the current index forwards by the amount of letters read in
            i += test.length() - 1;
	}
        return subStr;
}

At first I thought it was O(n2) because it has two loops. But I realized that the algorithm actually runs through the inputted string only once, because of i += test.length() - 1;
Am I correct in thinking that this algorithm has a time complexity of O(n)?

🌐
GitHub
github.com › rootusercop › TimeComplexityOfPredefinedMethodsInJava › blob › master › String, StringBuilder and StringBuffer class methods
TimeComplexityOfPredefinedMethodsInJava/String, StringBuilder and StringBuffer class methods at master · rootusercop/TimeComplexityOfPredefinedMethodsInJava
because ALL CLASSES AND INTERFACES in Java have equals() method · Worst case is O(n), unless the two strings are the same object in which case it's O(1). (Although in this case n refers to the number of matching characters in the two strings starting · from the first character, not the total length of the string).
Author   rootusercop
Top answer
1 of 3
17

For every call to String.concat(), a new string instance is created. To create that instance, the contents of the previous string needs to be copied to the new one plus the contents of the concatenated string. This is done for every string in the collection. So if you look at in in terms of how many strings are concatenated (and not the characters copied), you're copying the contents of the n strings by the time you reach the nth iteration and all that matters is the worst case (the last iteration). Therefore it has \$O(n^2)\$ performance.

2 of 3
2

As Jeff points out a new string is created every time you do += on the string.
And thus correctly explains why the complexity is O(2)

The key point is the java.lang.String is not mutable.

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

So any attempt to modify it generated a completely new string (which to programmers in most other languages is strange).

The solution is to use the java.lang.StringBuffer. This behaves like most other languages string object and allows mutation. The objective is to build a string inside a StringBuffer and when you are finally finished covert this into a string.

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.