-2
"ab" + 'c' // String + char
"ab" + "c" // String + String of single char

What is the difference between these expressions?

  • Is there any impact on the performance?
  • Is there any difference in behavior on different Java versions?
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Slawomir Jaranowski
  • 7,381
  • 3
  • 25
  • 33
  • 2
    Querstions about performance on this level are basically pointless: The answer depends on so many factors (such as surrounding code, JVM version, JVM flags, ...) that no useful general answer can be given. – Joachim Sauer Jan 04 '21 at 18:44
  • I believe `javac` interns those. Did you check the bytecode generated for the concatenations outcome with `javap`? – terrorrussia-keeps-killing Jan 04 '21 at 18:45
  • `char` type is obsolete, unable to represent even half of the characters defined in Unicode. Use code point integer numbers or a `CharSequence` such as `String`. – Basil Bourque Jan 04 '21 at 18:47
  • 4
    @BasilBourque: "`char` type is obsolete" is misleading at best and straight up wrong at worst. It does has the problems you mention, but that doesn't mean that using it is always a wrong choice. Also, downvoting without posting a comment is perfectly acceptable on SO. There are no rules to force people to comment. – Joachim Sauer Jan 04 '21 at 18:52
  • @JoachimSauer I never claimed any rule requiring a comment with a vote. I made a request. I don’t see the problem with this question, and asked for an explanation. Just as I would ask you how you use `char` to work with all of the 140,000 Unicode characters. – Basil Bourque Jan 04 '21 at 19:06
  • 2
    @BasilBourque: sometimes you don't **need** to work with all possible Unicode characters. When appending a hard-coded `:` or `<` or any other boring character to a string then a `char` constant does the job just fine. Yes, when iterating over a `String` you *usually* don't want to use `char` but even that depends on what you're trying to do. – Joachim Sauer Jan 04 '21 at 19:38

1 Answers1

-2

Using A + "B" is much slower than using A + 'B' based on this test result

Concatenate char literal ('x') vs single char string literal (“x”)

Test Result:

averageing to:

a+'B': 4608ms

a+"B": 5167ms

Sibin Rasiya
  • 1,132
  • 1
  • 11
  • 15