Skip to main content
Tweeted twitter.com/#!/StackProgrammer/status/405642410765873152
typo corrected
Link
gnat
  • 20.5k
  • 29
  • 117
  • 309

How many strings are created in memory when concatinatingconcatenating strings in Java?

Formatting, spelling
Source Link
user40980
user40980

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"

  1. ""
  2. "a"
  3. "a"
  4. "aa"
  5. "a"
  6. "aaa"
  7. "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?

I was asked about immutable strings in Java. I was tasked with writing a function that concatted 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 gasrbage collection does not happen. My thoughts for n=3 was "" "a" "a" "aa" "a" "aaa" "a"

Essentially 2 strings are created in each iteration of the loop. However, the answer was n^2. What strings will be created in memory by this function and why is that way?

I was asked about immutable strings in Java. I was tasked with writing a function that 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 garbage collection does not happen. My thoughts for n=3 was

  1. ""
  2. "a"
  3. "a"
  4. "aa"
  5. "a"
  6. "aaa"
  7. "a"

Essentially 2 strings are created in each iteration of the loop. However, the answer was n2. What strings will be created in memory by this function and why is that way?

Source Link
ahalbert
  • 343
  • 1
  • 2
  • 8

How many strings are created in memory when concatinating strings in Java?

I was asked about immutable strings in Java. I was tasked with writing a function that concatted 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 gasrbage collection does not happen. My thoughts for n=3 was "" "a" "a" "aa" "a" "aaa" "a"

Essentially 2 strings are created in each iteration of the loop. However, the answer was n^2. What strings will be created in memory by this function and why is that way?