简体   繁体   中英

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";

?

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;

U can use it in two diferent ways : String s2=s1+'c'; and char x = 'c'; String s2 = s1 + x; char x = 'c'; String s2 = s1 + x;

Both approaches are ok but if you are going into the details then perhaps

String s2=s1+'c';

will take a little less memory than the second way because char is just two bytes while String requires 8+ bytes. But I don't think that such nuances are important in most cases and also I'm not even sure that this difference will exist at all because JVM may optimize it

Java automatically does the conversion for you, so it doesn't really matter, but I'd personally just use a string (double quotes) just because I personally prefer to minimize the 'automatic stuff' that happens if I can prevent it.

Also, if you ever decide that 'c' should be 'csomething', then you'll have to change it into a boudle quote anyway.

But I suppose I'm just nitpicking...

Those are 2 different types of casting: implicit casting and explicit casting .

String s2=s1+'c';

This is a implicit casting, which means that the magic is done by the compiler (no overhead).

String s2=s1+"c";

This is a explicit casting, because "c" is converted to an object like:

Object o = "c";
String s2 = (String) o;

This means that the conversion must be checked for null-pointers, which will create an overhead.

Therefore, while both ways works, I prefer casting from character ('c') because that will create less overhead!

source: http://www.javaworld.com/article/2076555/build-ci-sdlc/java-performance-programming--part-2--the-cost-of-casting.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM