{"id":3826,"date":"2022-08-20T18:52:01","date_gmt":"2022-08-20T13:22:01","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/"},"modified":"2022-08-20T18:52:01","modified_gmt":"2022-08-20T13:22:01","slug":"solved-what-is-a-nullpointerexception-and-how-do-i-fix-it","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/","title":{"rendered":"(Solved) What is a NullPointerException, and how do I fix it?"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-218510\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"218510\" data-parentid=\"218384\" data-score=\"4114\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>There are two overarching types of variables in Java:<\/p>\n<ol>\n<li>\n<p><em>Primitives<\/em>: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type <code>int<\/code> or <code>char<\/code> are primitives.<\/p>\n<\/li>\n<li>\n<p><em>References<\/em>: variables that contain the memory address of an <code>Object<\/code> i.e. variables that <em>refer<\/em> to an <code>Object<\/code>. If you want to manipulate the <code>Object<\/code> that a reference variable refers to you must <em>dereference<\/em> it. Dereferencing usually entails using <code>.<\/code> to access a method or field, or using <code>[<\/code> to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type <code>Object<\/code> are references.<\/p>\n<\/li>\n<\/ol>\n<p>Consider the following code where you declare a variable of <em>primitive<\/em> type <code>int<\/code> and don&#8217;t initialize it:<\/p>\n<pre class=\"lang-java prettyprint-override\"><code>int x;\nint y = x + x;\n<\/code><\/pre>\n<p>These two lines will crash the program because no value is specified for <code>x<\/code> and we are trying to use <code>x<\/code>&#8216;s value to specify <code>y<\/code>. All primitives have to be initialized to a usable value before they are manipulated.<\/p>\n<p>Now here is where things get interesting. <em>Reference<\/em> variables can be set to <code>null<\/code> which means &#8220;<strong>I am referencing <em>nothing<\/em><\/strong>&#8220;. You can get a <code>null<\/code> value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to <code>null<\/code>).<\/p>\n<p>If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to <em>dereference<\/em> it you get a <code>NullPointerException<\/code>.<\/p>\n<p>The <code>NullPointerException<\/code> (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.<\/p>\n<p>Take the following code:<\/p>\n<pre><code>Integer num;\nnum = new Integer(10);\n<\/code><\/pre>\n<p>The first line declares a variable named <code>num<\/code>, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to <code>null<\/code>.<\/p>\n<p>In the second line, the <code>new<\/code> keyword is used to instantiate (or create) an object of type <code>Integer<\/code>, and the reference variable <code>num<\/code> is assigned to that <code>Integer<\/code> object.<\/p>\n<p>If you attempt to dereference <code>num<\/code> <em>before<\/em> creating the object you get a <code>NullPointerException<\/code>. In the most trivial cases, the compiler will catch the problem and let you know that &#8220;<code>num may not have been initialized<\/code>,&#8221; but sometimes you may write code that does not directly create the object.<\/p>\n<p>For instance, you may have a method as follows:<\/p>\n<pre><code>public void doSomething(SomeObject obj) {\n   \/\/ Do something to obj, assumes obj is not null\n   obj.myMethod();\n}\n<\/code><\/pre>\n<p>In which case, you are not creating the object <code>obj<\/code>, but rather assuming that it was created before the <code>doSomething()<\/code> method was called. Note, it is possible to call the method like this:<\/p>\n<pre><code>doSomething(null);\n<\/code><\/pre>\n<p>In which case, <code>obj<\/code> is <code>null<\/code>, and the statement <code>obj.myMethod()<\/code> will throw a <code>NullPointerException<\/code>.<\/p>\n<p>If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the <code>NullPointerException<\/code> because it&#8217;s a programmer error and the programmer will need that information for debugging purposes.<\/p>\n<p>In addition to <code>NullPointerException<\/code>s thrown as a result of the method&#8217;s logic, you can also check the method arguments for <code>null<\/code> values and throw NPEs explicitly by adding something like the following near the beginning of a method:<\/p>\n<pre><code>\/\/ Throws an NPE with a custom error message if obj is null\nObjects.requireNonNull(obj, \"obj must not be null\");\n<\/code><\/pre>\n<p>Note that it&#8217;s helpful to say in your error message clearly <em>which<\/em> object cannot be <code>null<\/code>. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless <code>obj<\/code> is reassigned, it is not null and can be dereferenced safely.<\/p>\n<p>Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a <strong>null parameter<\/strong> and behave differently. You should also explain this in the documentation. For example, <code>doSomething()<\/code> could be written as:<\/p>\n<pre><code>\/**\n  * @param obj An optional foo for ____. May be null, in which case\n  *  the result will be ____.\n  *\/\npublic void doSomething(SomeObject obj) {\n    if(obj == null) {\n       \/\/ Do something\n    } else {\n       \/\/ Do something else\n    }\n}\n<\/code><\/pre>\n<p>Finally, How to pinpoint the exception &amp; cause using Stack Trace<\/p>\n<blockquote>\n<p>What methods\/tools can be used to determine the cause so that you stop<br \/>\nthe exception from causing the program to terminate prematurely?<\/p>\n<\/blockquote>\n<p>Sonar with find bugs can detect NPE.<br \/>\nCan sonar catch null pointer exceptions caused by JVM Dynamically<\/p>\n<p>Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.<\/p>\n<p>In Java 14, the following is a sample NullPointerException Exception message:<\/p>\n<blockquote>\n<p>in thread &#8220;main&#8221; java.lang.NullPointerException: Cannot invoke &#8220;java.util.List.size()&#8221; because &#8220;list&#8221; is null<\/p>\n<\/blockquote><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">24<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved What is a NullPointerException, and how do I fix it? <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] There are two overarching types of variables in Java: Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives. References: variables that contain &#8230; <a title=\"(Solved) What is a NullPointerException, and how do I fix it?\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/\" aria-label=\"More on (Solved) What is a NullPointerException, and how do I fix it?\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[323,328],"class_list":["post-3826","post","type-post","status-publish","format-standard","hentry","category-solved","tag-java","tag-nullpointerexception"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>(Solved) What is a NullPointerException, and how do I fix it? - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"(Solved) What is a NullPointerException, and how do I fix it? - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] There are two overarching types of variables in Java: Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives. References: variables that contain ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-08-20T13:22:01+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"(Solved) What is a NullPointerException, and how do I fix it?\",\"datePublished\":\"2022-08-20T13:22:01+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/\"},\"wordCount\":759,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"java\",\"nullpointerexception\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/\",\"name\":\"(Solved) What is a NullPointerException, and how do I fix it? - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-08-20T13:22:01+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"(Solved) What is a NullPointerException, and how do I fix it?\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"(Solved) What is a NullPointerException, and how do I fix it? - JassWeb","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:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/","og_locale":"en_US","og_type":"article","og_title":"(Solved) What is a NullPointerException, and how do I fix it? - JassWeb","og_description":"[ad_1] There are two overarching types of variables in Java: Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives. References: variables that contain ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/","og_site_name":"JassWeb","article_published_time":"2022-08-20T13:22:01+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"(Solved) What is a NullPointerException, and how do I fix it?","datePublished":"2022-08-20T13:22:01+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/"},"wordCount":759,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["java","nullpointerexception"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/","url":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/","name":"(Solved) What is a NullPointerException, and how do I fix it? - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-08-20T13:22:01+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-what-is-a-nullpointerexception-and-how-do-i-fix-it\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"(Solved) What is a NullPointerException, and how do I fix it?"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/3826","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=3826"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/3826\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=3826"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=3826"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=3826"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}