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.

8
  • 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. Commented Jan 7, 2016 at 14:50
  • @JarrodRoberson question is not a duplicate of the one you linked ! Commented Jan 7, 2016 at 14:51
  • @Hans would you mind providing the rule key raising the issue? Commented Jan 7, 2016 at 14:51
  • @benzonico - damn copy paste in windows sucks! Commented Jan 7, 2016 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. Commented Jan 7, 2016 at 14:54

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.