Preferred way of declaring and converting primitives to strings
java
Solution
The best all-round approach, which will work for anything, is:
String s = String.valueOf(x);
Here `x` can be a primitive or an object, which (importantly) may be `null`.
Edit: The hackaliciuos way is:
X + "";
Although note that this is not very efficient, because it compiles to:
new StringBuilder().append(x).append("").toString();
And the call to `.append(x)` invokes `String.valueOf(x)` anyway.
Note that arrays need special treatment:
String s = Arrays.toString(array);
Problem
I have 3 options: - Declare `double member` and later when I have to pass `String` use `member + ""`. - Declare `double member` and later when I have to pass `String` use `Double.toString(member)`. - Declare `Double member = 0.0` and later when I have to pass `String` use `member.toString()`. My opinions: - The shortest one. However, `member + ""` will be converted to `new StringBuilder().append(member).append("").toString()`, which seems not elegant. - In `Double.toString(member)` I don't like that it doesn't start from the word `member`, which is the most important. We only need to convert it. It's better if `member` is in the beginning, because I pay most attention to the beginning of word. Quick glance and I know "ah, ok I'm passing member". And with `Double.toString(member)` my very first concentration goes to "ah, ok... a Double, we are doing toString... of a member! Ah ok". - `member.toString()` looks fine and it can be typed even faster then + "", because of autocompletion in Eclipse. However, objects are much slower then primitives. Reference. What is the best option? Maybe there are some other options?