Question

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?

Was it helpful?

Solution

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());

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top