J. Doe J. Doe - 29 days ago 17
Java Question

Quote marks when concatenating string with a single character

What kind of quote marks should I choose for a single character when I concatenate it with a string?

String s1="string";


Should I use

String s2=s1+'c';


Or

String s2=s1+"c";


?

Answer

You can use both! Give it a try!

"Why?" you ask. The magic here is the + operator.

When + is used with strings, it automatically turns the other operand into a string! That's why it can be used with 'c', a character literal. It can also be used with "c" because of course, "c" is a string literal.

Not only that, you can even add integers to a string:

String s2=s1+1;