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 Java Objects Delivering the MVP Exceptions

Is it bad practice to use + instead of %s

Would this be bad to do in a string:

String var = "World";

console.printf("Hello, "+var+"!");

Or do I always need to do

String var "World";

console.printf("Hello, %s!", var);

2 Answers

Jason Anders
MOD
Jason Anders
Treehouse Moderator 145,860 Points

Hi Ethan,

Concatenation (your first example) and Interpolation (second example) are two different ways of constructing a string with variables. Sometimes only one will work... other times both will work but one is usually better.

In your example, it doesn't make that much of a difference, although Interpolation would still be better.
But what if you were to have 3 or 4 or 7 variables to add? Do you really want to type "string " + variable + " string " + variable ... or would you rather "%s, <string goes here> %s %s!", variable1, variable2, variable 3.
Or what if there is a more complex formatting needed inside of the string... your concatenated string could span many, many + signs and "".
Finally, there is the subject of readability. Even with your example, the concatenated string is much more difficult to read in code than the interpolated one. With the concatenated one (even with better spacing), takes an extra minute to see what it's purpose or output will be.

So, while sometimes concatenation is fine, it usually is not the best way. In fact, I don't really see it used that often. In my opinion, yes, concatenation is "bad practice" and one should use interpolation unless absolutely necessary otherwise.

Keep Coding! :) :dizzy:

Thank you!