I’m trying to understand if this code below creates 12 objects for a string like “stephan”
public String reverse(String str) {
if ((null == str) || (str.length() <= 1)) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
This recursively reverses a string. I understand how it works. But I was thinking if there is a relationship in this case between the length of the strings and number of string objects created through concatenation?
Yes, it will create tons of string objects.
Every recursive call to “reverse()” will create 2:
str.substring(1)will create a new String objectreverse()call will create a new string for its return value, but we will NOT count that since that’s counted when analyzing that recursive call (e.g. it will be the string from bullet point #3 from the nextreverse()call).And since Java Strings are immutable, adding a char via “
+” will create a second String object.Therefore, for a string of length N, it will create (N-1)*2 objects (since a reverse of 1-char string does NOT create new strings); so for “stephan”‘s 7 characters, it will create 6*2=12 string objects.