Since myObject.toString()
fails when myObject
is null
(throws a NullPointerException
), it is safer to do myObject+""
, since it's essentially doing String.valueOf(myObject).concat("")
, which doesn't fail, but would instead result in the String "null"
.
However, is this a good practice? My first thought is that it seems like it might take longer to perform, since it's implicitly calling two methods, but it does help guarantee software that doesn't crash.
You certainly can do myObject+""
. But as you already know, that requires some extra method invocation. That will depend upon the application you're using it in. Will that extra method invocation be a bottle-neck for the application? I guess that is rarely an issue. Or, to avoid that extra method call, you can directly use String#valueOf()
method. But that would depend upon how you want to handle null
s. I would certainly not proceed normally in these circumstances. At least log a message indicating null
reference.
Also, if you're already on Java 7, then you can use Objects.toString(Object)
method, that handles null
for you. Again, that method returns "null"
for null
references.
So, now it's your call. I've given you some option. You might want to throw exception, log message and proceed with "null"
string, or some default string like ""
.