3

In Java I can convert an int to a string by "" + intValue. Sonarqube and sonarlint flag this as inappropriate.

Why is this inappropriate. As far as I know Integer.toString(intValue) is more verbose and does the same.

I can imagine to flag it if not "" but Object x is used as in x + intValue where x is initialized as an integer. Ran into something like that with Javascript code.

Hans
  • 467
  • 4
  • 12
  • because that is the most incorrect, naive way of converting an `int` ( or any other `Object` ) to a `String` representation that you can pick. This has been discourage for over a decade at this point. –  Jan 07 '16 at 14:50
  • @JarrodRoberson question is not a duplicate of the one you linked ! – benzonico Jan 07 '16 at 14:51
  • @Hans would you mind providing the rule key raising the issue? – benzonico Jan 07 '16 at 14:51
  • @benzonico - damn copy paste in windows sucks! –  Jan 07 '16 at 14:53
  • 5
    [This is the duplicate that I was trying to copy paste as the close reason. The accepted answer answers this as well.](http://stackoverflow.com/questions/10976731/convert-integer-double-to-string-in-java) –  Jan 07 '16 at 14:54
  • Sounds more like it :) – benzonico Jan 07 '16 at 14:58
  • There are older duplicates, seems like ""+42 is optimized but ""+intValue not. Hoped that compiler had advanced more since I came back to the Duke force from .NET. – Hans Jan 07 '16 at 15:46
  • It's because the java compiler is lazy. If the value is a constant (iconst_x or ldc) then the compiler can merge and inline. However, because it's a variable, the compiler can't/won't bother checking whether it's possible to inline into one statement – samczsun Jan 07 '16 at 15:50

1 Answers1

8

With regards to why it's bad, Java automatically optimizes String concatenation to use StringBuilder instead. This means that by doing this

"" + d

You're actually doing

new StringBuilder().append(d).toString();

And if you do

d + ""

You end up compiling

new StringBuilder(String.valueOf(d)).toString();

Which is a pretty big waste of resources relative to just calling

String.valueOf(d);
samczsun
  • 1,014
  • 6
  • 16