0

I have written some code and used a string that I concatentated using the += (as I only do it a couple of times.

Later on I used another string and used the concat() function. and the concatenation didn't work.

So I wrote a little method in Junit (with eclipse)...

@Test
public void StingConcatTest(){

    String str = "";

    str += "hello ";
    str += " and goodbye";

    String conc="";
    conc.concat("hello ");
    conc.concat(" and goodbye");
    System.out.println("str is: " + str + "\nconc is: "+ conc);

The output is...

str is: hello  and goodbye
conc is: 

So either I'm going mad, I'm doing something wrong (most likely), there is an issue in JUNIT, or there is a problem with my JRE / eclipse or something.

Note that stringbuilders are working fine.

David.

2
  • 2
    Google must be broken again. ;) Commented Aug 31, 2012 at 15:33
  • @peter I did search google, and no responses said had a good response like the one from nambari below. Commented Aug 31, 2012 at 21:44

6 Answers 6

7

Ok, we see this question at least couple of times a day.

Strings are immutable, so all operations on String results in new String.

conc= conc.concat("hello "); you need to reassign result to string again

Sign up to request clarification or add additional context in comments.

1 Comment

Ok I feel stupid. End of the day and not enough refreshments.
3

You have to try with:

String conc="";
conc = conc.concat("hello ");
conc = conc.concat(" and goodbye");
System.out.println("str is: " + str + "\nconc is: "+ conc);

For sake of optimization you can write:

String conc="";
conc = conc.concat("hello ").concat(" and goodbye");
System.out.println("str is: " + str + "\nconc is: "+ conc);

1 Comment

String is ALWAYS constant. When you use these methods (like concat()) you just create a NEW object String.
2

If you plan on concatenating multiple Strings you could also use StringBuilder:

StringBuilder builder = new StringBuilder();
builder.append("hello");
builder.append(" blabla");
builder.append(" and goodbye");
System.out.println(builder.toString());

Comments

1

concat returns a String. It doesn't update the original String.

Comments

0

concat() returns the concatenated string.

public static void main(String [] args) {
    String s = "foo";

    String x = s.concat("bar");

    System.out.println(x);
}

Comments

0

String.concat doesn't change the string it is called on - it returns a new string which is the string and the argument concatenated together.

By the way: string concatenation using concat or += is not very performant. You should use the class StringBuilder instead.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.