I was asked about immutable strings in Java. I was tasked with writing a function that concatted concatenated a number of "a"s to a string.
What I wrote:
public String foo(int n) {
String s = "";
for (int i = 0; i < n; i++) {
s = s + "a"
}
return s;
}
I was then asked how many strings this program would generate, assuming gasrbagegarbage collection does not happen. My thoughts for n=3 was "" "a" "a" "aa" "a" "aaa" "a"
- ""
- "a"
- "a"
- "aa"
- "a"
- "aaa"
- "a"
Essentially 2 strings are created in each iteration of the loop. However, the answer was n^2 n2. What strings will be created in memory by this function and why is that way?