{"id":634,"date":"2018-04-01T01:48:50","date_gmt":"2018-04-01T00:48:50","guid":{"rendered":"https:\/\/dassiorleando.com\/?p=634"},"modified":"2018-04-01T01:48:50","modified_gmt":"2018-04-01T00:48:50","slug":"safely-tostring-a-java-object","status":"publish","type":"post","link":"https:\/\/dassiorleando.com\/fr\/safely-tostring-a-java-object\/","title":{"rendered":"Safely toString a Java object"},"content":{"rendered":"<h2 class=\"wp-block-heading\">Overview<\/h2>\n\n\n\n<p>In this little article, we will see how to get the string representation(tostring) of an object cautiously, that means avoiding NullPointerException.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Context<\/h2>\n\n\n\n<p>Getting the <strong>String<\/strong> representation of a Java object is something we often do for logging, debugging, or simply for overview\u00a0purposes.<\/p>\n\n\n\n<p>For a null object, we will be directed to a <strong>NullPointerException<\/strong>, as the toString is using the\u00a0fields of the object.<\/p>\n\n\n\n<p>A catch-up\u00a0of this without even checking for nullity before is just by using the <strong>String.valueOf(object)<\/strong> method instead of directly using object.toString().<\/p>\n\n\n\n<p>Here is the content of String.valueOf generated by IntelliJ:<\/p>\n\n\n\n<pre class=\"wp-block-syntaxhighlighter-code\">\/**\n * Returns the string representation of the {@code Object} argument.\n *\n * @param   obj   an {@code Object}.\n * @return  if the argument is {@code null}, then a string equal to\n *          {@code &quot;null&quot;}; otherwise, the value of\n *          {@code obj.toString()} is returned.\n * @see     java.lang.Object#toString()\n *\/\npublic static String valueOf(Object obj) {\n    return (obj == null) ? &quot;null&quot; : obj.toString();\n}<\/pre>\n\n\n\n<p>Where it&#8217;s clearly described how the null is catches on before the toString.<\/p>\n\n\n\n<p>This function is also wrapped up into the Objects utility function accessible via the: <strong>Objects.toString(Object o)<\/strong>, more readable.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">A Real Life Example<\/h2>\n\n\n\n<p>Let&#8217;s suppose your application logic, among others, is using two models with some properties where one depends on the other:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>ObjectB:&nbsp;propB<\/li>\n\n\n\n<li>ObjectA:&nbsp;propA,&nbsp;objectB1 and&nbsp;objectB2<\/li>\n<\/ul>\n\n\n\n<p>Considering that the dependency objectB2 is optional&nbsp;and somewhere in your code you would like to toString each property of&nbsp;ObjectA(even the optional one).<\/p>\n\n\n\n<p>Here is an approach without the need of checking for nullity:<\/p>\n\n\n\n<p><strong>ObjectB<\/strong> class:<\/p>\n\n\n\n<pre class=\"wp-block-syntaxhighlighter-code\">public class ObjectB {\n    private String propB;\n \n    public ObjectB(String propB) {\n        this.propB = propB;\n    }\n \n    \/\/ Getters and setters\n \n    @Override\n    public String toString() {\n        return &quot;ObjectB{&quot; +\n                &quot;propB=&#039;&quot; + propB + &#039;\\&#039;&#039; +\n                &#039;}&#039;;\n    }\n}<\/pre>\n\n\n\n<p><strong>ObjectA<\/strong> class has objectB2 as an optional property:<\/p>\n\n\n\n<pre class=\"wp-block-syntaxhighlighter-code\">public class ObjectB {\n    private String propB;\n \n    public ObjectB(String propB) {\n        this.propB = propB;\n    }\n \n    \/\/ Getters and setters\n \n    @Override\n    public String toString() {\n        return &quot;ObjectB{&quot; +\n                &quot;propB=&#039;&quot; + propB + &#039;\\&#039;&#039; +\n                &#039;}&#039;;\n    }\n}<\/pre>\n\n\n\n<p>The following <strong>JUnit<\/strong> test illustrates how we now proceed to come out with a safe string representation of ObjectA&#8217;s instances:<\/p>\n\n\n\n<pre class=\"wp-block-syntaxhighlighter-code\">@Test\npublic void safeToStringTest() {\n    ObjectB objectB = new ObjectB(&quot;Fake propB&quot;);\n    ObjectA objectA = new ObjectA(&quot;Fake propA&quot;, objectB);\n\n    String stringObjectA = Objects.toString(objectA);\n    System.out.println(stringObjectA);\n\n    assertNull(objectA.getObjectB2());\n    assertTrue(stringObjectA.contains(&quot;objectB2=null&quot;));\n}<\/pre>\n\n\n\n<p>The printed string of our ObjectA into the console is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">ObjectA{propA=&#039;Fake propA&#039;, objectB1=ObjectB{propB=&#039;Fake propB&#039;}, objectB2=null}<\/pre>\n\n\n\n<p>More usages of the <strong>Objects<\/strong> class can be found on this <a href=\"https:\/\/dassiorleando.com\/fr\/jdk-7-objects-class-check-nullity-throw-npe\/\">page<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>To sum up, we have seen here a proper way to safely toString an object with embed properties.<\/p>\n\n\n\n<p>As usual, the code is available in the&nbsp;<a href=\"https:\/\/github.com\/dassiorleando\/jse\">GitHub repo<\/a>.<\/p>","protected":false},"excerpt":{"rendered":"<p>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 String representation of a Java object is something we often do for logging, debugging, or simply for overview\u00a0purposes. For a null object, we will be directed to a NullPointerException, as [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":662,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[29],"tags":[30,34,35],"class_list":["post-634","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java","tag-objects","tag-tostring"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.0 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to safely toString a Java object<\/title>\n<meta name=\"description\" content=\"In this little article, we will see how to get the string representation(tostring) of an object cautiously, that means avoiding NullPointerException. Getting the string representation of a Java object is something we often do for logging, debugging, or simply for overview purpose.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/dassiorleando.com\/fr\/safely-tostring-a-java-object\/\" \/>\n<meta property=\"og:locale\" content=\"fr_CA\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to safely toString a Java object\" \/>\n<meta property=\"og:description\" content=\"In this little article, we will see how to get the string representation(tostring) of an object cautiously, that means avoiding NullPointerException. Getting the string representation of a Java object is something we often do for logging, debugging, or simply for overview purpose.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/dassiorleando.com\/fr\/safely-tostring-a-java-object\/\" \/>\n<meta property=\"og:site_name\" content=\"Orleando Dassi\" \/>\n<meta property=\"article:published_time\" content=\"2018-04-01T00:48:50+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/dassiorleando.com\/wp-content\/uploads\/2018\/04\/safely-tostring-java-object.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1024\" \/>\n\t<meta property=\"og:image:height\" content=\"768\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Orl\u00e9ando Dassi\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@dassiorleando\" \/>\n<meta name=\"twitter:site\" content=\"@dassiorleando\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Orl\u00e9ando Dassi\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/\"},\"author\":{\"name\":\"Orl\u00e9ando Dassi\",\"@id\":\"https:\/\/dassiorleando.com\/#\/schema\/person\/4862911e9cf93aa12f17875f7b7b1c5e\"},\"headline\":\"Safely toString a Java object\",\"datePublished\":\"2018-04-01T00:48:50+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/\"},\"wordCount\":297,\"commentCount\":1,\"publisher\":{\"@id\":\"https:\/\/dassiorleando.com\/#\/schema\/person\/4862911e9cf93aa12f17875f7b7b1c5e\"},\"image\":{\"@id\":\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/dassiorleando.com\/wp-content\/uploads\/2018\/04\/safely-tostring-java-object.png\",\"keywords\":[\"JAVA\",\"Objects\",\"tostring\"],\"articleSection\":[\"Java\"],\"inLanguage\":\"fr-CA\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/\",\"url\":\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/\",\"name\":\"How to safely toString a Java object\",\"isPartOf\":{\"@id\":\"https:\/\/dassiorleando.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/dassiorleando.com\/wp-content\/uploads\/2018\/04\/safely-tostring-java-object.png\",\"datePublished\":\"2018-04-01T00:48:50+00:00\",\"description\":\"In this little article, we will see how to get the string representation(tostring) of an object cautiously, that means avoiding NullPointerException. Getting the string representation of a Java object is something we often do for logging, debugging, or simply for overview purpose.\",\"breadcrumb\":{\"@id\":\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#breadcrumb\"},\"inLanguage\":\"fr-CA\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"fr-CA\",\"@id\":\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#primaryimage\",\"url\":\"https:\/\/dassiorleando.com\/wp-content\/uploads\/2018\/04\/safely-tostring-java-object.png\",\"contentUrl\":\"https:\/\/dassiorleando.com\/wp-content\/uploads\/2018\/04\/safely-tostring-java-object.png\",\"width\":1024,\"height\":768,\"caption\":\"Safely tostring a java object\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/dassiorleando.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Safely toString a Java object\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/dassiorleando.com\/#website\",\"url\":\"https:\/\/dassiorleando.com\/\",\"name\":\"Orleando Dassi\",\"description\":\"My personal portfolio and resume\",\"publisher\":{\"@id\":\"https:\/\/dassiorleando.com\/#\/schema\/person\/4862911e9cf93aa12f17875f7b7b1c5e\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/dassiorleando.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"fr-CA\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/dassiorleando.com\/#\/schema\/person\/4862911e9cf93aa12f17875f7b7b1c5e\",\"name\":\"Orl\u00e9ando Dassi\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"fr-CA\",\"@id\":\"https:\/\/dassiorleando.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/dassiorleando.com\/wp-content\/uploads\/2025\/01\/Orleando-Dassi-Consultant-Quebec.webp\",\"contentUrl\":\"https:\/\/dassiorleando.com\/wp-content\/uploads\/2025\/01\/Orleando-Dassi-Consultant-Quebec.webp\",\"width\":1643,\"height\":1747,\"caption\":\"Orl\u00e9ando Dassi\"},\"logo\":{\"@id\":\"https:\/\/dassiorleando.com\/#\/schema\/person\/image\/\"},\"description\":\"I'm a Solutions Architect with 10 years of experience who is constantly learning while impacting the community by producing technical articles\/videos, building projects, and conducting tech mentoring\/coaching sessions. What describes me the most is my flexibility.\",\"sameAs\":[\"https:\/\/dassiorleando.com\/\",\"https:\/\/www.instagram.com\/dassiorleando\/\",\"https:\/\/www.linkedin.com\/in\/dassi-orleando-257b04ab\/\",\"https:\/\/x.com\/dassiorleando\",\"https:\/\/www.youtube.com\/@dassiorleando\"],\"url\":\"https:\/\/dassiorleando.com\/fr\/author\/dassiorleando\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to safely toString a Java object","description":"In this little article, we will see how to get the string representation(tostring) of an object cautiously, that means avoiding NullPointerException. Getting the string representation of a Java object is something we often do for logging, debugging, or simply for overview purpose.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/dassiorleando.com\/fr\/safely-tostring-a-java-object\/","og_locale":"fr_CA","og_type":"article","og_title":"How to safely toString a Java object","og_description":"In this little article, we will see how to get the string representation(tostring) of an object cautiously, that means avoiding NullPointerException. Getting the string representation of a Java object is something we often do for logging, debugging, or simply for overview purpose.","og_url":"https:\/\/dassiorleando.com\/fr\/safely-tostring-a-java-object\/","og_site_name":"Orleando Dassi","article_published_time":"2018-04-01T00:48:50+00:00","og_image":[{"width":1024,"height":768,"url":"https:\/\/dassiorleando.com\/wp-content\/uploads\/2018\/04\/safely-tostring-java-object.png","type":"image\/png"}],"author":"Orl\u00e9ando Dassi","twitter_card":"summary_large_image","twitter_creator":"@dassiorleando","twitter_site":"@dassiorleando","twitter_misc":{"Written by":"Orl\u00e9ando Dassi","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#article","isPartOf":{"@id":"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/"},"author":{"name":"Orl\u00e9ando Dassi","@id":"https:\/\/dassiorleando.com\/#\/schema\/person\/4862911e9cf93aa12f17875f7b7b1c5e"},"headline":"Safely toString a Java object","datePublished":"2018-04-01T00:48:50+00:00","mainEntityOfPage":{"@id":"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/"},"wordCount":297,"commentCount":1,"publisher":{"@id":"https:\/\/dassiorleando.com\/#\/schema\/person\/4862911e9cf93aa12f17875f7b7b1c5e"},"image":{"@id":"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#primaryimage"},"thumbnailUrl":"https:\/\/dassiorleando.com\/wp-content\/uploads\/2018\/04\/safely-tostring-java-object.png","keywords":["JAVA","Objects","tostring"],"articleSection":["Java"],"inLanguage":"fr-CA","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/","url":"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/","name":"How to safely toString a Java object","isPartOf":{"@id":"https:\/\/dassiorleando.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#primaryimage"},"image":{"@id":"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#primaryimage"},"thumbnailUrl":"https:\/\/dassiorleando.com\/wp-content\/uploads\/2018\/04\/safely-tostring-java-object.png","datePublished":"2018-04-01T00:48:50+00:00","description":"In this little article, we will see how to get the string representation(tostring) of an object cautiously, that means avoiding NullPointerException. Getting the string representation of a Java object is something we often do for logging, debugging, or simply for overview purpose.","breadcrumb":{"@id":"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#breadcrumb"},"inLanguage":"fr-CA","potentialAction":[{"@type":"ReadAction","target":["https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/"]}]},{"@type":"ImageObject","inLanguage":"fr-CA","@id":"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#primaryimage","url":"https:\/\/dassiorleando.com\/wp-content\/uploads\/2018\/04\/safely-tostring-java-object.png","contentUrl":"https:\/\/dassiorleando.com\/wp-content\/uploads\/2018\/04\/safely-tostring-java-object.png","width":1024,"height":768,"caption":"Safely tostring a java object"},{"@type":"BreadcrumbList","@id":"https:\/\/dassiorleando.com\/safely-tostring-a-java-object\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/dassiorleando.com\/"},{"@type":"ListItem","position":2,"name":"Safely toString a Java object"}]},{"@type":"WebSite","@id":"https:\/\/dassiorleando.com\/#website","url":"https:\/\/dassiorleando.com\/","name":"Orleando Dassi","description":"My personal portfolio and resume","publisher":{"@id":"https:\/\/dassiorleando.com\/#\/schema\/person\/4862911e9cf93aa12f17875f7b7b1c5e"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/dassiorleando.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"fr-CA"},{"@type":["Person","Organization"],"@id":"https:\/\/dassiorleando.com\/#\/schema\/person\/4862911e9cf93aa12f17875f7b7b1c5e","name":"Orl\u00e9ando Dassi","image":{"@type":"ImageObject","inLanguage":"fr-CA","@id":"https:\/\/dassiorleando.com\/#\/schema\/person\/image\/","url":"https:\/\/dassiorleando.com\/wp-content\/uploads\/2025\/01\/Orleando-Dassi-Consultant-Quebec.webp","contentUrl":"https:\/\/dassiorleando.com\/wp-content\/uploads\/2025\/01\/Orleando-Dassi-Consultant-Quebec.webp","width":1643,"height":1747,"caption":"Orl\u00e9ando Dassi"},"logo":{"@id":"https:\/\/dassiorleando.com\/#\/schema\/person\/image\/"},"description":"I'm a Solutions Architect with 10 years of experience who is constantly learning while impacting the community by producing technical articles\/videos, building projects, and conducting tech mentoring\/coaching sessions. What describes me the most is my flexibility.","sameAs":["https:\/\/dassiorleando.com\/","https:\/\/www.instagram.com\/dassiorleando\/","https:\/\/www.linkedin.com\/in\/dassi-orleando-257b04ab\/","https:\/\/x.com\/dassiorleando","https:\/\/www.youtube.com\/@dassiorleando"],"url":"https:\/\/dassiorleando.com\/fr\/author\/dassiorleando\/"}]}},"_links":{"self":[{"href":"https:\/\/dassiorleando.com\/fr\/wp-json\/wp\/v2\/posts\/634","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/dassiorleando.com\/fr\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dassiorleando.com\/fr\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dassiorleando.com\/fr\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/dassiorleando.com\/fr\/wp-json\/wp\/v2\/comments?post=634"}],"version-history":[{"count":0,"href":"https:\/\/dassiorleando.com\/fr\/wp-json\/wp\/v2\/posts\/634\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/dassiorleando.com\/fr\/wp-json\/wp\/v2\/media\/662"}],"wp:attachment":[{"href":"https:\/\/dassiorleando.com\/fr\/wp-json\/wp\/v2\/media?parent=634"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dassiorleando.com\/fr\/wp-json\/wp\/v2\/categories?post=634"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dassiorleando.com\/fr\/wp-json\/wp\/v2\/tags?post=634"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}