According to the tool PMD, the following is a bad practice:
String s = "" + 123; // bad
String t = Integer.toString(456); // ok
This is an inefficient way to convert any type to a `String`.
Why is it a bad thing to do?
valueOf will transform a given object that is null to the String "null" , whereas . toString() will throw a NullPointerException . The compiler will use String. valueOf by default when something like String s = "" + (...); is used.
The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.
An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .
It is inefficient, as it involves an unneeded string concatenation, thus the creation of one or two extra String
objects - although I believe the JIT can optimize it away.
To me the bigger problem is that the code is less clear. Calling toString
is a standard idiom, understandable to every Java developer (hopefully :-), so you should prefer this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With