Why string concatenation with pip line return nothing(empty string) in java?
String product="";
for(Tar t:tars){
product.concat(t.product.concat("|"));
}
System.out.println(product);
result is just nothing(empty string).
Why string concatenation with pip line return nothing(empty string) in java?
String product="";
for(Tar t:tars){
product.concat(t.product.concat("|"));
}
System.out.println(product);
result is just nothing(empty string).
String#concat returns a concatenated String, it doesn't modify it. Strings are immutable in Java.
So...
product = product.concat(t.product.concat("|"));
But, I suggest using StringBuilder where String copying happens in a loop.
Use StringBuilder instead.
StringBuilder product=new StringBuilder();
for(Tar t:tars){
product.append(t.product).append("|");
}
System.out.println(product.toString());
If the collection is fairly large, I would recommend using a StringBuilder to build the desired string, instead of using string concatenation. It will improve performance, albeit slightly.
See also StringBuilder vs String concatenation in toString() in Java.
Also, straight from the horse's mouth,
Concatenates the specified string to the end of this string.
If the length of the argument string is
0, then thisStringobject is returned. Otherwise, a newStringobject is created, representing a character sequence that is the concatenation of the character sequence represented by thisStringobject and the character sequence represented by the argument string.