Monday, October 13, 2008

String.valueOf(Object obj) vs. Object.toString()

I'm programming with Java for more than 10 years now and I have always used Object.toString() to print out any kind of objects, usually for debugging and logging purposes. Looking at code written by others, this seems to be pretty usual. But there is a big problem: the object may be null. In this case, the call to Object.toString() will result in a NullPointerException. Sometimes ;-) I'm well aware of this problem, so I usually wrote ((obj==null)?"null":obj.toString()). By accident I found this nice function a day ago: String.valueOf(Object obj). What does it do? It's a static method and it looks like that: return (obj == null) ? "null" : obj.toString();. Looks pretty familiar. Why didn't I found this method earlier? Carnival barker: "Are you using this method? If not, start today and bugs like this will become history!" So, I would recommend to use String.valueOf(Object obj) rather than Object.toString(). But there are others (e.g. here or there) who recommend to prefer Object.toString(), because you can save one method call. IMHO this is the wrong place to start optimizations. I also found some tutorials which explain that you can use one or the other without discussing the differences. Maybe that's why I needed 10 years to find this nice static method.