{"id":6047,"date":"2021-04-06T19:30:13","date_gmt":"2021-04-06T14:00:13","guid":{"rendered":"https:\/\/java2blog.com\/?p=6047"},"modified":"2021-10-18T17:45:32","modified_gmt":"2021-10-18T12:15:32","slug":"exception-thread-main-java-lang-nullpointerexception","status":"publish","type":"post","link":"https:\/\/java2blog.com\/exception-thread-main-java-lang-nullpointerexception\/","title":{"rendered":"[Solved] Exception in thread &#8220;main&#8221; java.lang.NullPointerException"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#Reasons_for_NullPointerException\">Reasons for NullPointerException<\/a><ul><li><a href=\"#1_Invoking_the_instance_method_of_anullobject\">1. Invoking the instance method of a\u00a0null\u00a0object<\/a><\/li><li><a href=\"#2_Accessing_or_modifying_the_field_of_anull_object\">2. Accessing or modifying the field of a\u00a0null object.<\/a><\/li><li><a href=\"#3_Taking_the_length_of_nullas_if_it_were_an_array\">3. Taking the length of null\u00a0as if it were an array.<\/a><\/li><li><a href=\"#4_Accessing_or_modifying_the_slots_ofnullas_if_it_were_an_array\">4. Accessing or modifying the slots of\u00a0null\u00a0as if it were an array.<\/a><\/li><li><a href=\"#5_Throwingnullas_if_it_were_aThrowablevalue\">5. Throwing\u00a0null\u00a0as if it were a\u00a0Throwable\u00a0value.<\/a><\/li><li><a href=\"#6_When_you_add_null_to_Collections_which_do_not_allow_nulls_such_as_ConcurrentHashMap\">6. When you add null to Collections which do not allow nulls such as ConcurrentHashMap<\/a><\/li><li><a href=\"#7_Trying_to_synchronize_using_null_object\">7. Trying to synchronize using null object.<\/a><\/li><\/ul><\/li><li><a href=\"#Detection_of_NullPointerException\">Detection of NullPointerException<\/a><\/li><li><a href=\"#Fix_NullPointerException\">Fix NullPointerException<\/a><ul><li><a href=\"#1_Null_check\">1. Null check<\/a><\/li><li><a href=\"#2_Do_null_check_as_well_before_putting_key_or_value_in_Collection_which_do_not_allow_null\">2. Do null check as well before putting key or value in Collection which do not allow null<\/a><\/li><\/ul><\/li><li><a href=\"#Best_practices_for_avoiding_NullPointerException\">Best practices for avoiding NullPointerException<\/a><ul><li><a href=\"#1_String_comparison\">1. String comparison<\/a><\/li><li><a href=\"#2_Use_Optional\">2. Use Optional<\/a><\/li><li><a href=\"#3_Use_ternary_opertor\">3. Use ternary opertor<\/a><\/li><li><a href=\"#4_Keep_check_on_arguments_of_method\">4. Keep check on arguments of method<\/a><\/li><li><a href=\"#5_Use_StringUtils_from_Apache_Common\">5. Use StringUtils from Apache Common<\/a><\/li><\/ul><\/li><\/ul><\/div>\n<p>In this tutorial, we will see the most frequent java <a href=\"https:\/\/java2blog.com\/exception-handling-java\/\">exception<\/a> i.e. <code>Exception in thread main java.lang.NullPointerException<\/code>. It is one of the Runtime Exception.<\/p>\n<p>Raise your hand if you ever got NullPointerException while working on java code. I am sure that this is the exception you might have encountered most frequently. You might also agree that NullPointerException is\u00a0pain for most of java developers(novice or expert), but there is not much we can do about them, because this is the price we need to pay for convenient or unavoidable null references.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"aligncenter wp-image-6063\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2018\/07\/NullPointerException-275x300.png\" alt=\"NullPointerException\" width=\"400\" height=\"437\" srcset=\"https:\/\/java2blog.com\/wp-content\/uploads\/2018\/07\/NullPointerException-275x300.png 275w, https:\/\/java2blog.com\/wp-content\/uploads\/2018\/07\/NullPointerException.png 594w\" sizes=\"(max-width: 400px) 100vw, 400px\" \/><\/p>\n<h2><span id=\"Reasons_for_NullPointerException\">Reasons for NullPointerException<\/span><\/h2>\n<p>Reasons for NullPointerException as defined by Java docs.<\/p>\n<ul>\n<li>Invoking the instance method of a\u00a0null\u00a0object.<\/li>\n<li>Accessing or modifying the field of a\u00a0null object.<\/li>\n<li>Taking the length of null\u00a0as if it were an array.<\/li>\n<li>Accessing or modifying the slots of\u00a0null\u00a0as if it were an array.<\/li>\n<li>Throwing\u00a0null\u00a0as if it were a\u00a0Throwable\u00a0value.<\/li>\n<li>When you add null to Collections which do not allow nulls such as [ConcurrentHashMap](https:\/\/java2blog.com\/concurrenthashmap-in-java\/ &#8220;ConcurrentHashMap&#8221;)<\/li>\n<li>Trying to synchronize using null object.<\/li>\n<\/ul>\n<p>Let&#8217;s understand each of these in detail. I am creating a Employee class which we are going to use in our examples.<\/p>\n<pre class=\"java\" name=\"code\" title=\"Employee.java\">package org.arpit.java2blog;\n\npublic class Employee {\n    String name;\n    int age;\n\n    public Employee()\n    {\n\n    }\n\n    public Employee(String name, int age) {\n        this.name=name;\n        this.age=age;\n    }\n    public String getName() {\n        return name;\n    }\n    public void setName(String name) {\n        this.name = name;\n    }\n    public int getAge() {\n        return age;\n    }\n    public void setAge(int age) {\n        this.age = age;\n    }\n\n}\n<\/pre>\n<h3><span id=\"1_Invoking_the_instance_method_of_anullobject\"><span style=\"color: #f89820;\">1. Invoking the instance method of a\u00a0null\u00a0object<\/span><\/span><\/h3>\n<p>This is most obvious one.<\/p>\n<pre class=\"java\" name=\"code\" mark=\"7\" title=\"InvokingMethodOnNullMain.java\">package org.arpit.java2blog;\npublic class InvokingMethodOnNullMain {\n\n    public static void main(String[] args) {\n        Employee e1=null;\n        String name = e1.getName();\n        System.out.println(\"Employee Name: \"+ name);\n    }\n}\n<\/pre>\n<p>When you run above program, you will get below output.<\/p>\n<div class=\"content-box-green\">Exception in thread &#8220;main&#8221; java.lang.NullPointerException<br \/>\nat org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)<\/div>\n<p>As you can see, e1 is null at line 7 and we are calling getMethod on it, thats why we are getting <code>Exception in thread \" main java.lang.NullPointerException<\/code> here.<\/p>\n<h3><span id=\"2_Accessing_or_modifying_the_field_of_anull_object\"><span style=\"color: #f89820;\">2. Accessing or modifying the field of a\u00a0null object.<\/span><\/span><\/h3>\n<p>It is very much similar to calling instance method on null.<\/p>\n<pre class=\"java\" name=\"code\" mark=\"8\" title=\"NullFieldExampleMain.java\">package org.arpit.java2blog;\n\npublic class NullFieldExampleMain {\n\n    public static void main(String[] args) {\n        Employee e1=null;\n        String name = e1.name;\n        System.out.println(\"Employee Name: \"+ name);\n    }\n\n}\n<\/pre>\n<p>When you run above program, you will get below output.<\/p>\n<div class=\"content-box-green\">Exception in thread &#8220;main&#8221; java.lang.NullPointerException<br \/>\nat org.arpit.java2blog.NullFieldExampleMain.main(InvokingMethodOnNullMain.java:8)<\/div>\n<p>As you can see, e1 is null at line 8 and we are accessing name field of e1, thats why we are getting NullPointerException here.<\/p>\n<h3><span id=\"3_Taking_the_length_of_nullas_if_it_were_an_array\"><span style=\"color: #f89820;\">3. Taking the length of null\u00a0as if it were an array.<\/span><\/span><\/h3>\n<p>When you try to get length of null array, you will get NullPointerException.<\/p>\n<pre class=\"java\" name=\"code\" title=\"NullArrayLengthMain.java\">package org.arpit.java2blog;\n\npublic class NullArrayLengthMain {\n\n    public static void main(String[] args) {\n        Employee[] arrEmp=null;\n\n        int length = arrEmp.length;\n        System.out.println(\"Length of array: \"+length);\n    }\n}\n<\/pre>\n<p>When you run above program, you will get below output.<\/p>\n<div class=\"content-box-green\">Exception in thread &#8220;main&#8221; java.lang.NullPointerException<br \/>\nat org.arpit.java2blog.NullArrayLengthMain.main(InvokingMethodOnNullMain.java:9)<\/div>\n<h3><span id=\"4_Accessing_or_modifying_the_slots_ofnullas_if_it_were_an_array\"><span style=\"color: #f89820;\">4. Accessing or modifying the slots of\u00a0null\u00a0as if it were an array.<\/span><\/span><\/h3>\n<p>When you try to access or modify null slot in array.Let&#8217;s understand with the help of example.<\/p>\n<pre class=\"java\" name=\"code\" mark=\"8\">package org.arpit.java2blog;\n\npublic class InvokingMethodOnNullMain {\n\n    public static void main(String[] args) {\n        Employee[] arrEmp=null; \n        System.out.println(arrEmp[3]);\n    }\n}\n<\/pre>\n<p>When you run above program, you will get below output.<\/p>\n<div class=\"content-box-green\">Exception in thread &#8220;main&#8221; java.lang.NullPointerException<br \/>\nat org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:8)<\/div>\n<h3><span id=\"5_Throwingnullas_if_it_were_aThrowablevalue\"><span style=\"color: #f89820;\">5. Throwing\u00a0null\u00a0as if it were a\u00a0Throwable\u00a0value.<\/span><\/span><\/h3>\n<p>When you throw null as Throwable.<\/p>\n<pre class=\"java\" name=\"code\" mark=\"7\">package org.arpit.java2blog;\n\npublic class InvokingMethodOnNullMain {\n\n    public static void main(String[] args) {\n        throw null;\n    }\n}\n\n<\/pre>\n<p>When you run above program, you will get below output.<\/p>\n<div class=\"content-box-green\">Exception in thread &#8220;main&#8221; java.lang.NullPointerException<br \/>\nat org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)<\/div>\n<h3><span id=\"6_When_you_add_null_to_Collections_which_do_not_allow_nulls_such_as_ConcurrentHashMap\"><span style=\"color: #f89820;\">6. When you add null to Collections which do not allow nulls such as ConcurrentHashMap<\/span><\/span><\/h3>\n<pre class=\"java\" name=\"code\" mark=\"10\">package org.arpit.java2blog;\n\nimport java.util.concurrent.ConcurrentHashMap;\n\npublic class InvokingMethodOnNullMain {\n\n    public static void main(String[] args) {\n        ConcurrentHashMap&lt;String, String&gt; map=new ConcurrentHashMap&lt;&gt;();\n        map.put(null, \"Dummy\");\n    }\n}\n<\/pre>\n<p>When you run above program, you will get below output.<\/p>\n<div class=\"content-box-green\">Exception in thread &#8220;main&#8221; java.lang.NullPointerException<br \/>\nat java.base\/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1022)<br \/>\nat java.base\/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1017)<br \/>\nat org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:10)<\/div>\n<h3><span id=\"7_Trying_to_synchronize_using_null_object\"><span style=\"color: #f89820;\">7. Trying to synchronize using null object.<\/span><\/span><\/h3>\n<p>When you synchronize on null object, you will get NullPointerException<\/p>\n<pre class=\"java\" name=\"code\" mark=\"10\">package org.arpit.java2blog;\n\nimport java.util.concurrent.ConcurrentHashMap;\n\npublic class InvokingMethodOnNullMain {\n\n    public static void main(String[] args) {\n        Object obj=null;\n        synchronized (obj) {\n            ConcurrentHashMap&lt;String, String&gt; map=new ConcurrentHashMap&lt;&gt;();\n            map.put(\"Dummy\", \"value\");\n        }\n    }\n}\n<\/pre>\n<p>When you run above program, you will get below output.<\/p>\n<div class=\"content-box-green\">Exception in thread &#8220;main&#8221; java.lang.NullPointerException<br \/>\nat org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:10)<\/div>\n<hr \/>\n<h2><span id=\"Detection_of_NullPointerException\">Detection of NullPointerException<\/span><\/h2>\n<p>It is easier to detect NullPointerException. Check exception trace, it will tell you class name, method name and line number.Go to that line number and check what can be the reason for NullPointerException.<\/p>\n<hr \/>\n<h2><span id=\"Fix_NullPointerException\">Fix NullPointerException<\/span><\/h2>\n<p>Let&#8217;s take above scenrios and fix NullPointerException.<\/p>\n<h3><span id=\"1_Null_check\"><span style=\"color: #f89820;\">1. Null check<\/span><\/span><\/h3>\n<p>check null before calling method or field.<\/p>\n<pre class=\"java\" name=\"code\">package org.arpit.java2blog;\npublic class InvokingMethodOnNullMain {\n\n    public static void main(String[] args) {\n        Employee e1=null;\n        if(e1!=null)\n        {\n            String name = e1.getName();\n            System.out.println(\"Employee Name: \"+ name);\n        }\n    }\n}\n<\/pre>\n<p>When you run above program, you won&#8217;t get NullPointerExcpetion.<\/p>\n<h3><span id=\"2_Do_null_check_as_well_before_putting_key_or_value_in_Collection_which_do_not_allow_null\"><span style=\"color: #f89820;\">2. Do null check as well before putting key or value in Collection which do not allow null<\/span><\/span><\/h3>\n<hr \/>\n<h2><span id=\"Best_practices_for_avoiding_NullPointerException\">Best practices for avoiding NullPointerException<\/span><\/h2>\n<h3><span id=\"1_String_comparison\"><span style=\"color: #f89820;\">1. String comparison<\/span><\/span><\/h3>\n<p>This is most frequent reason for <code>Exception in thread main java.lang.NullPointerException<\/code>, let&#8217;s understand with the help of example.<\/p>\n<pre class=\"java\" name=\"code\">package org.arpit.java2blog;\n\npublic class StringComparisonMain {\n\n    public static void main(String[] args) {\n        Employee e1=new Employee();\n\n        if(e1.getName().equalsIgnoreCase(\"John\"))\n        {\n            System.out.println(\"Employee Name is John\");\n        }\n    }\n}\n<\/pre>\n<p>As we did not set name of Employee e1, we will get NullPointerException here.<br \/>\nWhen you run above program, you will get below output.<\/p>\n<div class=\"content-box-green\">Exception in thread &#8220;main&#8221; java.lang.NullPointerException<br \/>\nat org.arpit.java2blog.StringComparisonMain.main(StringComparisonMain.java:8)<\/div>\n<p>You can change logic as below.<\/p>\n<pre class=\"java\" name=\"code\" mark=\"9\">package org.arpit.java2blog;\n\npublic class StringComparisonMain {\n\n    public static void main(String[] args) {\n        Employee e1=new Employee();\n\n        if(\"John\".equalsIgnoreCase(e1.getName()))\n        {\n            System.out.println(\"Employee Name is John\");\n        }\n    }\n}\n<\/pre>\n<p>This will avoid <code>Exception in thread main java.lang.NullPointerException<\/code>.<br \/>\nPlease note that it may cause unexpected behavior due to null. If name cannot be null at all for Employee, then don&#8217;t use above method as it will ignore null names in this case.<\/p>\n<h3><span id=\"2_Use_Optional\"><span style=\"color: #f89820;\">2. Use Optional<\/span><\/span><\/h3>\n<p>Java 8 has introduced a new class called <a href=\"https:\/\/java2blog.com\/java-8-optional\/\" target=\"_blank\" rel=\"noopener\">Optional<\/a>.In general, we do not find any value in method, we return null from it and it becomes pain for caller to check for null to use it.<br \/>\nFor example:<\/p>\n<pre class=\"java\" name=\"code\">public static Employee findEmployee(List&lt;Employee employeeList,String name)\n{\n    for(Employee e:employeeList)\n    {\n        if(e.getName().equalsIgnoreCase(name))\n        {\n            return e;\n        }\n    }\n    return null;\n}\n<\/pre>\n<p>As you can see, if we did not find <code>employee<\/code> in <code>employeeList<\/code>, we are returning null from <code>findEmployee()<\/code> method. The caller will get\u00a0 employee object from <code>findEmployee()<\/code> method and may call getName() method which will in turn raise NullPointerException.You can use Optional to avoid such situations.<\/p>\n<pre class=\"java\" name=\"code\">package org.arpit.java2blog;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional;\n\npublic class JavaOptionalMain {\n\n    public static void main(String[] args)\n    {\n        List&lt;Employee&gt; employeeList = createEmployeeList();\n        Optional&lt;Employee&gt; employeeOpt = findEmployee(employeeList,\"John\");\n        if(employeeOpt.isPresent())\n        {\n            Employee employee = employeeOpt.get();\n            System.out.println(\"Employee name: \"+employee.getName());\n        }\n        else\n        {\n            System.out.println(\"There is no employee with name John\");\n        }\n    }\n\n    public static Optional&lt;Employee&gt; findEmployee(List&lt;Employee&gt; employeeList,String name)\n    {\n        for(Employee e:employeeList)\n        {\n            if(e.getName().equalsIgnoreCase(name))\n            {\n                return Optional.of(e);\n            }\n        }\n        return Optional.empty();\n    }\n    public static List&lt;Employee&gt; createEmployeeList()\n    {\n        List&lt;Employee&gt; employeeList=new ArrayList&lt;&gt;();\n\n        Employee e1=new Employee(\"Adam\",23);\n        Employee e2=new Employee(\"Dave\",34);\n        Employee e3=new Employee(\"Carl\",45);\n        Employee e4=new Employee(\"Mohan\",29);\n        Employee e5=new Employee(\"Paresh\",30);\n\n        employeeList.add(e1);\n        employeeList.add(e2);\n        employeeList.add(e3);\n        employeeList.add(e4);\n        employeeList.add(e5);\n\n        return employeeList;\n    }\n}\n<\/pre>\n<div class=\"content-box-green\">There is no employee with name John<\/div>\n<p>It gives indication to caller than returned value can be null.<\/p>\n<h3><span id=\"3_Use_ternary_opertor\"><span style=\"color: #f89820;\">3. Use ternary opertor<\/span><\/span><\/h3>\n<p>You can use ternary operation to check for null.<\/p>\n<pre class=\"java\" name=\"code\">package org.arpit.java2blog;\npublic class InvokingMethodOnNullMain {\n\n    public static void main(String[] args) {\n        Employee e1=null;\n\n        String name = e1==null?e1.getName():\"\";\n        System.out.println(\"Employee Name: \"+ name);\n\n    }\n}\n<\/pre>\n<p>As you can see, we won&#8217;t get NullPointerException here.<\/p>\n<h3><span id=\"4_Keep_check_on_arguments_of_method\"><span style=\"color: #f89820;\">4. Keep check on arguments of method<\/span><\/span><\/h3>\n<pre class=\"java\" name=\"code\">package org.arpit.java2blog;\npublic class InvokingMethodOnNullMain {\n\n    public static void main(String[] args) {\n        String str=null;\n        int len=getLength(str);\n        System.out.println(\"Length of String:\"+ len);\n    }\n\n    public static int getLength(String str)\n    {\n        if(str!=null)\n        {\n            return str.length();\n        }\n        else\n        {\n            return 0;\n        }\n    }\n}\n<\/pre>\n<h3><span id=\"5_Use_StringUtils_from_Apache_Common\"><span style=\"color: #f89820;\">5. Use StringUtils from Apache Common<\/span><\/span><\/h3>\n<p>You can use <code>StringUtils<\/code> class to take care of lots of String null and empty String check. Sometimes you need to check if String is null or empty, you can use isEmpty method from <code>StringUtils<\/code> to take care of it.<\/p>\n<p>That&#8217;s all about Exception in thread &quot;main&quot; java.lang.NullPointerException in java.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsReasons for NullPointerException1. Invoking the instance method of a\u00a0null\u00a0object2. Accessing or modifying the field of a\u00a0null object.3. Taking the length of null\u00a0as if it were an array.4. Accessing or modifying the slots of\u00a0null\u00a0as if it were an array.5. Throwing\u00a0null\u00a0as if it were a\u00a0Throwable\u00a0value.6. When you add null to Collections which do not allow [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[171],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/6047"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=6047"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/6047\/revisions"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=6047"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=6047"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=6047"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}