0

I have a code that is:

String str = "hi";
String[] strArray = new String[5];
for(int c = 0;c < 5;c++){
    str += strArray[c];
}

Although with 5 strings I can do one by one? but what if there are 50, or even 5 hundred? This type of += gave me an error, so how do I add up all the strings in the array properly?

zbz.lvlv
  • 3,597
  • 6
  • 34
  • 38

2 Answers2

1

I'm not sure what error you got - I ran your example an it works fine. If you print the resulting str though, you get hinullnullnullnullnull because you haven't put anything in the strArray yet.

String concatenation with the += operator is not efficient in Java: to do this efficiently, you need to use the StringBuilder class.

Example of how to do that with the StringBuilder class:

    StringBuilder builder = new StringBuilder();
    String[] strArray = new String[50];
    // Put something in the strings in strArray
    for (int c = 0; c < strArray.length; c++) {
        builder.append(strArray[c]);
    }
    String str = builder.toString();
Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79
  • I think they optimized that away a while ago. See [1] Now, you can do string concatenation and internally, the StringBuilder will be used. [1]http://stackoverflow.com/questions/14927630/java-string-concat-vs-stringbuilder-optimised-so-what-should-i-do – Radu Mar 23 '14 at 03:56
  • I think that you read the answer to that question wrong. The accepted answer actually says to *use* `StringBuilder` rather than concatenating using the `+` operator - if you're doing it in a loop, like the OP is asking. – Erwin Bolwidt Mar 23 '14 at 03:57
1

Instead of using += on String objects use StringBuilder. Reason being in JAVA appending string creates immutable String objects each time which leads to memory explosion. On the other hand, StringBuilder is mutable object, you append to your heart's content & then return a String object.

    StringBuilder stringBuilder = new StringBuilder();
    String[] strArray = new String[5]; //or some big number
    for(int c = 0;c < 5;c++)
    {
        stringBuilder.append(strArray[c]);
    }
    System.out.println(stringBuilder.toString());
Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264