3

A small question, but one I'm genuinely curious about.

Is there anything inherently better or worse with

"a string with a char: " + 'x'

compared to

"a string with a char: " + "x"

?

They both work, but I am wondering if either has any performance or efficiency implications--minor as they may be.

Thanks.

aliteralmind
  • 19,847
  • 17
  • 77
  • 108
  • It won't be any performance impact since Java will use a `StringBuilder` behind the scenes to concatenate them. – Luiggi Mendoza Nov 20 '13 at 15:06
  • Do you mean that the code literally says that (append two literals), or do you have some of those values as variables? The compiler will probably make the former the same, but the latter could be different. – Tim S. Nov 20 '13 at 15:10
  • @LuiggiMendoza could be StringBuffer though if he is using a JDK prior to 5.0 – jantristanmilan Nov 20 '13 at 15:11
  • 1
    [this](http://stackoverflow.com/questions/11408427/how-does-the-string-class-override-the-operator) may help you better understand the concept. – Nishant Nov 20 '13 at 15:16
  • both concatenations are performed by the compiler. – DwB Nov 20 '13 at 16:16
  • Append two literal strings with a plus. Thanks to all for the responses. There is NO difference. – aliteralmind Nov 20 '13 at 18:37
  • 1
    Whilst there may be no performance issue, as described at http://stackoverflow.com/a/18925251/449347 there are benefits in using `'x'` ; if you only meant to type one character the compiler will give you a friendly error that you have made a typo. – k1eran May 06 '14 at 16:47

2 Answers2

2
public void test(){ 
    String str1 = "appl" + 'e';
    String str2 = "banan" + "a";
}

No change in byte code:

public void test();
    Code:
       0: ldc           #2                  // String apple
       2: astore_1      
       3: ldc           #3                  // String banana
       5: astore_2      
       6: return

I should mention that if you put the concatenation in a loop then StringBuilder will be used for both. That's all.

Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
0

I am very sure that they will both generate the same efficient bytecode. Compilers are clever

So if there would be a difference (which I am not sure of), the compiler will erase it

LionC
  • 3,106
  • 1
  • 22
  • 31
  • I've read concatenation happens during compilation so at least in the OP's specific example it will be turned in to `"a string with a char: x"` in both cases. – Radiodef Nov 20 '13 at 15:13
  • Thats what I was talking about, as this can trivially be transformed into the best form anyways, it will be – LionC Nov 20 '13 at 15:14