Difference between Long.toString(i) vs i + ""
we often come across a scenario where in we need to pass a String representation of a primitive and More often then not we use
WrapperClass.toString() ;
and sometimes we usually write
i + "";
if we check to toString implementation of an开发者_开发问答y wrapper class it creates a new String object every time we call it. and same is also true for primitive + "" (as Concatenation during runtime will create new String Object)
So is there any difference between them or they are just an alternative ways to convert a primitive to a String object;
Personally I like String.valueOf(i)
:
- You can use it with all types (even non-primitives)
- It's null-safe (assuming you're happy with a string value of "null" when converting a value of null)
- It expresses your intention far better than
"" + i
- that code expresses string concatenation, which isn't what you're after at all.
Good intentions.
Writing i + "";
, you're possibly leaving it up to your code's future maintainer (which could very well be you) to figure out what that output will be.
WrapperClass.toString();
is more explicit and, although more verbose, its intentions are clearer. Besides, weak typing isn't what you'd normally see in Java, so I suggest you stick to writing idiomatic Java code.
After compilation, emitted bytecode will most likely be the same or similar. After jitting and during runtime, you can expect the differences to be effectively nullified.
So, at the end, it's a matter of style, although I'd suggest using the more verbose version of your code.
Functionally, they are the same. The difference is, that i + "";
is basically using a side-effect to archive its purpose, which might make it more difficult to understand for beginners.
精彩评论