Use concat instead:
String str = "test"; str = str.concat("test2"); str = str.concat("test3"); str = str.concat("test4"); str = str.concat("test5");Use a single line of concatenation, which will create a single StringBuilder. Remember that each ; will create another StringBuilder:. Note that in the concatenation of constant Strings below, the Java compiler will create a single String. However, if you add one or more String variables, then the StringBuilder will be created.
String str = "test" + "test2" + "test3" + "test4" + "test5";Create a StringBuilder yourself, do the concatenation, and REUSE the StringBuilder. This has the best performance, specially when doing things in a loop.
StringBuilder sb = new StringBuilder(512); for (int i = 0; i < 10000; i++) { sb.setLength(0); sb.append("test"); sb.append("test2"); sb.append("test3"); sb.append("test4"); sb.append("test5"); sb.append(i); String s = sb.toString(); }