0

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).

Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
itro
  • 7,006
  • 27
  • 78
  • 121
  • 8
    You have to assign the result of `concat()` to `product`, i.e. `product = product.concat(...)` – Baz Aug 21 '12 at 13:37
  • 1
    @HodeCode For my comment to be an answer, I would have to explain why... – Baz Aug 21 '12 at 13:40
  • @Baz Yeah but not much! All you need is something like Strings are immutable, hence that method returns a String created to represent the modification requested (eg. concat)? But anyway, I upvoted your comment! – Darius Aug 21 '12 at 13:46
  • @HodeCode Yeah, I know. I was just too lazy to formulate a proper answer. Thanks for the upvote anyways :) Besides, I am going for the "Pundit" badge :D – Baz Aug 21 '12 at 13:47

3 Answers3

9

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.

nullpotent
  • 9,162
  • 1
  • 31
  • 42
1

Use StringBuilder instead.

StringBuilder product=new StringBuilder();
for(Tar t:tars){
            product.append(t.product).append("|");
}
System.out.println(product.toString());
Piotr Gwiazda
  • 12,080
  • 13
  • 60
  • 91
1

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,

String#concat:

Concatenates the specified string to the end of this string.

If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.

Community
  • 1
  • 1
user1329572
  • 6,176
  • 5
  • 29
  • 39