Avoiding NPE Safely toString a Java object This article was originally posted . here Overview In this little article, we will see how to get the string representation(tostring) of an object cautiously, that means avoiding NullPointerException. Context Getting the representation of a object is something we often do for logging, debugging, or simply for overview purpose. String Java For a null object we will be directed to a NullPointerException, as the toString is using the fields of the object. A catch up of this without even check for nullity before is just by using the **String.valueOf(object)**method instead of directly using object.toString(). Here is the content of String.valueOf generated by IntelliJ: Where it’s clearly described how the null is catches on before the toString. This function is also wrapped up into the Objects utility function accessible via the: , more readable. Objects.toString(Object o) A real live example Let’s suppose your application logic, among others, is using two models with some properties where one depends on the other: ObjectB: propB ObjectA: propA, objectB1 and objectB2 Considering that the dependency objectB2 is optional and somewhere in your code you would like to toString each property of ObjectA(even the optional one). Here is an approach without the need of checking for nullity: class: ObjectB class has objectB2 as an optional property: ObjectA The following test illustrates how we now proceed to come out with a string representation of ObjectA’s instances: JUnit safe The printed string of our ObjectA into the console is: ObjectA{propA=’Fake propA’, objectB1=ObjectB{propB=’Fake propB’}, objectB2=null} More usages of the class can be found on this . Objects page Conclusion To sum up, we have seen here a proper way to safely toString an object with embed properties. As usual, the code is available in the . GitHub repo Thanks for reading this post, recommend and share if you enjoyed it. Follow me on , , and visit my . Facebook Twitter LinkedIn blog Cheers!