String valueOf vs concatenation with empty string

后端 未结 10 1725
说谎
说谎 2020-11-27 05:05

I am working in Java code optimization. I\'m unclear about the difference between String.valueOf or the +\"\" sign:

int intVar = 1;         


        
10条回答
  •  一个人的身影
    2020-11-27 05:52

    Ask yourself the purpose of the code. Is it to:

    • Concatenate an empty string with a value
    • Convert a value to a string

    It sounds much more like the latter to me... which is why I'd use String.valueOf. Whenever you can make your code read in the same way as you'd describe what you want to achieve, that's a good thing.

    Note that this works for all types, and will return "null" when passed a null reference rather than throwing a NullPointerException. If you're using a class (not an int as in this example) and you want it to throw an exception if it's null (e.g. because that represents a bug), call toString on the reference instead.

提交回复
热议问题