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 any 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;
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.