I am trying to concat String array values in a String, The below code does not work
private void newString() {
String str = "Split me";
String[] tokens = str.split("[ ]+");
String newStr = new String();
for(int i=0; i<tokens.length; i++){
newStr.concat(tokens[i]);
}
System.out.println("NEW STRING IS : " + newStr);
}
public static void main(String[] args){
Main m = new Main();
m.newString();
}
Stringis immutable. Naturally,String.concatreturns a brand newString.The way you’re trying to do it, the code should look like…
Now, the problem I have with this approach is that you’re doing a lot of copies of the
Stringdata. Eachconcatcopies all of the data ingluedas well as the data intoken. Now, think about the implications of that… I’m not a fan of premature optimization, but I believe the logical way to achieve this is to instead use aStringBuilderas follows…