Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

String concatenation?

I am not 100% sure I know what String Concatenation is, or how to use it. Here's what I know:

String example = "marshmallo";
char exampleTwo = 'w';
example += exampleTwo;
    return example;

Is 'example' now 'marshmallow', or am I missing something?

Any help would be greatly apreciated. Thanks! -Uriah P.S. Is that how you spell concatenation?

1 Answer

Hi Uriah!

Your code won't work, because you're trying to concatenate two different data types. You have to use the StringBuilder.

StringBuilder sb = new StringBuilder();
sb.append(example);
sb.append(exampleTwo);
example = sb.toString();
return example;

First I'm creating a new StringBuilder object. Then I'm using the append method to sort of concatenate the String and Char (which are two different data types). Lastly I'm assigning example a new value, which is the StringBuilder turned into a String. Of course I'm then returning example.

If you have any further question, feel free to ask!