{"id":7653,"date":"2013-12-23T17:41:43","date_gmt":"2013-12-23T15:41:43","guid":{"rendered":"http:\/\/examples.javacodegeeks.com\/?p=7653"},"modified":"2022-07-06T13:33:57","modified_gmt":"2022-07-06T10:33:57","slug":"java-lang-nullpointerexception-how-to-handle-null-pointer-exception","status":"publish","type":"post","link":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/","title":{"rendered":"java.lang.NullPointerException Example &#8211; How to handle Java Null Pointer Exception (with video)"},"content":{"rendered":"<p>In this post, we feature a comprehensive example of java.lang.NullPointerException &#8211; Java Null Pointer Exception. In Java, a special&nbsp;<code>null<\/code>&nbsp;value can be assigned to an object\u2019s reference and denotes that the object is currently pointing to&nbsp;an <strong>unknown<\/strong>&nbsp;piece of data. A&nbsp;java.lang.NullPointerException <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">is thrown<\/a> when an application is trying to use or access an object whose reference equals to&nbsp;<code>null<\/code>. The following cases throw Null Pointer exception:<\/p>\n<ul class=\"wp-block-list\">\n<li>Invoking a method from a&nbsp;<code>null<\/code>&nbsp;object.<\/li>\n<li>Accessing or modifying a&nbsp;<code>null<\/code>&nbsp;object\u2019s field.<\/li>\n<li>Taking the length of&nbsp;<code>null<\/code>, as if it were an array.<\/li>\n<li>Accessing or modifying the slots of&nbsp;<code>null<\/code>&nbsp;object, as if it were an array.<\/li>\n<li>Throwing&nbsp;<code>null<\/code>, as if it were a&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/Throwable.html\">Throwable<\/a><\/code>&nbsp;value.<\/li>\n<li>When you try to synchronize over a&nbsp;<code>null<\/code>&nbsp;object.<\/li>\n<\/ul>\n<p>The&nbsp; java.lang.NullPointerException&nbsp;is a&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/RuntimeException.html\">RuntimeException<\/a><\/code>&nbsp;and thus, the&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/technotes\/tools\/windows\/javac.html\">Javac<\/a><\/code>&nbsp;compiler does&nbsp;<strong>not<\/strong>&nbsp;force you to use a try-catch block to handle it appropriately.<\/p>\n<p>You can also check this tutorial in the following video:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large is-resized\"><a href=\"https:\/\/www.youtube.com\/watch?v=624TTmeO5SQ\"><img decoding=\"async\" src=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/07\/java.lang_.NullPointerException-Example-1024x576.jpg\" alt=\"\" class=\"wp-image-113849\" width=\"512\" height=\"288\" srcset=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/07\/java.lang_.NullPointerException-Example-1024x576.jpg 1024w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/07\/java.lang_.NullPointerException-Example-300x169.jpg 300w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/07\/java.lang_.NullPointerException-Example-768x432.jpg 768w, https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/07\/java.lang_.NullPointerException-Example.jpg 1280w\" sizes=\"(max-width: 512px) 100vw, 512px\" \/><\/a><figcaption>java.lang.NullPointerException Example &#8211; How to handle Java Null Pointer Exception<\/figcaption><\/figure>\n<\/div>\n<h2 class=\"wp-block-heading\" id=\"h-1-why-do-we-need-the-null-value\">1. Why do we need the null value?<\/h2>\n<p>As already mentioned,&nbsp;<code>null<\/code>&nbsp;is a special value used in Java. It is extremely useful in coding some design patterns, such as&nbsp;<a href=\"http:\/\/www.oodesign.com\/null-object-pattern.html\">Null Object pattern<\/a>&nbsp;and&nbsp;<a href=\"http:\/\/www.oodesign.com\/singleton-pattern.html\">Singleton pattern<\/a>. The Null Object pattern provides an object as a surrogate for the lack of an object of a given type. The Singleton pattern ensures that only one instance of a class is created and also, aims for providing a global point of access to the object.<\/p>\n<p>For example, a sample way to create&nbsp;<strong>at most one<\/strong>&nbsp;instance of a class is to declare all its constructors as private and then, create a public method that returns the unique instance of the class:<\/p>\n<p><span style=\"text-decoration: underline\"><em>TestSingleton.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">import java.util.UUID;\n \nclass Singleton {\n \n     private static Singleton single = null;\n     private String ID = null;\n \n     private Singleton() {\n          \/* Make it private, in order to prevent the creation of new instances of\n           * the Singleton class. *\/\n \n          ID = UUID.randomUUID().toString(); \/\/ Create a random ID.\n     }\n \n     public static Singleton getInstance() {\n          if (single == null)\n               single = new Singleton();\n \n          return single;\n     }\n \n     public String getID() {\n          return this.ID;\n     }\n}\n \npublic class TestSingleton {\n     public static void main(String[] args) {\n          Singleton s = Singleton.getInstance();\n          System.out.println(s.getID());\n     }\n}\n<\/pre>\n<p>In this example, we declare a static instance of the Singleton class. That instance is initialized at most once inside the&nbsp;<code>getInstance<\/code>&nbsp;method. Notice the use of the&nbsp;<code>null<\/code>&nbsp;value that enables the unique instance creation.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-2-how-to-avoid-the-java-lang-nullpointerexception\">2. How to avoid the java.lang.NullPointerException<\/h2>\n<p>In order to avoid the&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code>, ensure that all your objects are initialized properly, before you use them. Notice that, when you declare a reference variable, you are really creating a pointer to an object. You must verify that the pointer is not null, before you request the method or a field from the object.<\/p>\n<p>Also, if the exception is thrown, use the information residing in the exception\u2019s stack trace. The execution\u2019s stack trace is provided by the JVM, in order to enable the debugging of the application. Locate the method and the line where the exception was caught and then, figure out which reference equals to null in that specific line.<\/p>\n<p>In the rest of this section, we will describe some techniques that deal with the aforementioned exception. However, they do not eliminate the problem and the programmer should always be careful while coding an application.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-2-1-string-comparison-with-literals\">2.1 String comparison with literals<\/h3>\n<p>A very common case in an application\u2019s execution code involves the comparison between a String variable and a literal. The literal may be a String or the element of an Enum. Instead of invoking the method from the null object, consider invoking it from the literal. For example, observe the following case:<\/p>\n<pre class=\"brush:java\">String str = null;\nif(str.equals(\"Test\")) {\n     \/* The code here will not be reached, as an exception will be thrown. *\/\n}\n<\/pre>\n<p>The above code snippet will throw a&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code>. However, if we invoke the method from the literal, the execution flow continues normally:<\/p>\n<pre class=\"brush:java\">String str = null;\nif(\"Test\".equals(str)) {\n     \/* Correct use case. No exception will be thrown. *\/\n}\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-2-2-check-the-arguments-of-a-method\">2.2 Check the arguments of a method<\/h3>\n<p>Before executing the body of your own method, be sure to check its arguments for null values. Continue with the execution of the method, only when the arguments are properly checked. Otherwise, you can throw an&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/IllegalArgumentException.html\">IllegalArgumentException<\/a><\/code>&nbsp;and notify the calling method that something is wrong with the passed arguments.<div style=\"display:inline-block; margin: 15px 0;\"> <div id=\"adngin-JavaCodeGeeks_incontent_video-0\" style=\"display:inline-block;\"><\/div> <\/div><\/p>\n<p>For example:<\/p>\n<pre class=\"brush:java\">public static int getLength(String s) {\n     if (s == null)\n          throw new IllegalArgumentException(\"The argument cannot be null\");\n \n     return s.length();\n}\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-2-3-prefer-string-valueof-method-instead-of-tostring\">2.3 Prefer String.valueOf() method instead of toString()<\/h3>\n<p>When your application\u2019s code requires the String representation of an object, avoid using the object\u2019s&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/String.html#toString%28%29\">toString<\/a><\/code>&nbsp;method. If your object\u2019s reference equals to&nbsp;<code>null<\/code>, a&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code>&nbsp;will be thrown.<\/p>\n<p>Instead, consider using the static&nbsp;<code><a href=\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/String.html#toString%28%29\">String.valueOf<\/a><\/code>&nbsp;method, which does not throw any exceptions and prints&nbsp;<code>\"null\"<\/code>, in case the function\u2019s argument equals to&nbsp;<code>null<\/code>.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-2-4-use-the-ternary-operator\">2.4 Use the Ternary Operator<\/h3>\n<p>The&nbsp;<code><a href=\"https:\/\/en.wikipedia.org\/wiki\/%3F:\">ternary<\/a><\/code>&nbsp;operator can be very useful and can help us avoid the&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code>. The operator has the form:<\/p>\n<pre class=\"brush:java\">boolean expression ? value1 : value2;\n<\/pre>\n<p>First, the boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the&nbsp;<code>ternary<\/code>&nbsp;operator for handling null pointers as follows:<\/p>\n<pre class=\"brush:java\">String message = (str == null) ? \"\" : str.substring(0, 10);\n<\/pre>\n<p>The message variable will be empty if&nbsp;<code>str<\/code>\u2019s reference is null. Otherwise, if&nbsp;<code>str<\/code>&nbsp;points to actual data, the message will retrieve the first 10 characters of it.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-2-5-create-methods-that-return-empty-collections-instead-of-null\">2.5 Create methods that return empty collections instead of null<\/h3>\n<p>A very good technique is to create methods that return an empty collection, instead of a&nbsp;<code>null<\/code>&nbsp;value. Your application\u2019s code can iterate over the empty collection and use its methods and fields, without throwing a&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code>. For example:<\/p>\n<p><span style=\"text-decoration: underline\"><em>Example.java<\/em><\/span><\/p>\n<pre class=\"brush:java\">public class Example {\n     private static List numbers = null;\n \n     public static List getList() {\n          if (numbers == null)\n               return Collections.emptyList();\n          else\n               return numbers;\n     }\n}\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-2-6-make-use-of-apache-s-stringutils-class\">2.6 Make use of Apache\u2019s StringUtils class<\/h3>\n<p>Apache\u2019s&nbsp;<code><a href=\"https:\/\/commons.apache.org\/proper\/commons-lang\/\">Commons Lang<\/a><\/code>&nbsp;is a library that provides helper utilities for the&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/package-summary.html\">java.lang<\/a><\/code>&nbsp;API, such as String manipulation methods. A sample class that provides String manipulation is&nbsp;<code><a href=\"https:\/\/commons.apache.org\/proper\/commons-lang\/apidocs\/org\/apache\/commons\/lang3\/StringUtils.html\">StringUtils.java<\/a><\/code>, which handles&nbsp;<code>null<\/code>&nbsp;input Strings quietly.<\/p>\n<p>You can make use of the&nbsp;<code><a href=\"https:\/\/commons.apache.org\/proper\/commons-lang\/javadocs\/api-2.6\/org\/apache\/commons\/lang\/StringUtils.html#isNotEmpty%28java.lang.String%29\">StringUtils.isNotEmpty,<\/a><\/code>&nbsp;<code><a href=\"https:\/\/commons.apache.org\/proper\/commons-lang\/javadocs\/api-2.6\/org\/apache\/commons\/lang\/StringUtils.html#isEmpty%28java.lang.String%29\">StringUtils.IsEmpty<\/a><\/code>&nbsp;and&nbsp;<code><a href=\"https:\/\/commons.apache.org\/proper\/commons-lang\/javadocs\/api-2.6\/org\/apache\/commons\/lang\/StringUtils.html#equals(java.lang.String,%20java.lang.String)\">StringUtils.equals<\/a><\/code>&nbsp;methods, in order to avoid the&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code>. For example:<\/p>\n<pre class=\"brush:java\">if (StringUtils.isNotEmpty(str)) {\n     System.out.println(str.toString());\n}\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-2-7-use-the-contains-containskey-containsvalue-methods\">2.7 Use the contains(), containsKey(), containsValue() methods<\/h3>\n<p>If your application code makes use of collections, such as&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/util\/Map.html\">Maps<\/a><\/code>, consider using the contains,&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/util\/Map.html#containsKey%28java.lang.Object%29\">containsKey<\/a><\/code>&nbsp;and&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/util\/Map.html#containsValue%28java.lang.Object%29\">containsValue<\/a><\/code>&nbsp;methods. For example, retrieve the value of a specific key, after you have verified its existence in the map:<\/p>\n<pre class=\"brush:java\">Map map = \u2026\n\u2026\nString key = \u2026\nString value = map.get(key);\nSystem.out.println(value.toString()); \/\/ An exception will be thrown, if the value is null.\n<\/pre>\n<p>In the above snippet, we don\u2019t check if the key actually exists inside the&nbsp;<code>Map<\/code>&nbsp;and thus, the returned value can be&nbsp;<code>null<\/code>. The safest way is the following:<\/p>\n<pre class=\"brush:java\">Map map = \u2026\n\u2026\nString key = \u2026\nif(map.containsKey(key)) {\n     String value = map.get(key);\n     System.out.println(value.toString()); \/\/ No exception will be thrown.\n}\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-2-8-using-try-catch-block\">2.8 Using try-catch block<\/h3>\n<p>We can handle&nbsp;<a rel=\"noreferrer noopener\" target=\"_blank\" href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a>&nbsp;using the try-catch block. Let\u2019s take an example of comparing to the equality of two Strings.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Handling null using try-catch block<\/em><\/span><\/p>\n<pre class=\"brush:java\">\/\/ Initializing String variable with null value\nString nullString = null;\n\n\/\/ Checking if nullString.equals(any_string) or works fine.\ntry {\n    \/\/ This line of code throws NullPointerException\n    \/\/ because ptr is null\n    if (nullString.equals(\"any_string\"))\n        System.out.println(\"Both strings are same.\");\n    else\n        System.out.println(\"Both strings are same.\");\n} catch (NullPointerException e) {\n    System.out.println(\"NullPointerException occurred\");\n}\n<\/pre>\n<p>In the above example, we have created a string and assigned it with the null value. Later, we called the equals method on that string and it threw&nbsp; java.lang.NullPointerException which get caught in the catch-block. Here is the output of the above code snippet.<\/p>\n<p><span style=\"text-decoration: underline\"><em>Result<\/em><\/span><\/p>\n<pre class=\"brush:bash\">NullPointerException occurred\n<\/pre>\n<p>We can avoid the above exception by invoking method from the literal instead of invoking it from the null object as follows:<\/p>\n<p><span style=\"text-decoration: underline\"><em>Avoiding null using literal<\/em><\/span><\/p>\n<pre class=\"brush:java\">\/\/ Initializing String variable with null value\nString nullString = null;\n\n\/\/ Checking if \"any_string\".equals(nullString) or works fine.\ntry {\n    \/\/ This line of code throws NullPointerException\n    \/\/ because ptr is null\n    if (\"any_string\".equals(nullString))\n        System.out.println(\"Both strings are same.\");\n    else\n        System.out.println(\"Both strings are same.\");\n} catch (NullPointerException e) {\n    System.out.println(\"NullPointerException occurred\");\n}\n<\/pre>\n<p>In the above example, to avoid the above exception by invoking method from the literal instead of invoking it from the null object. Below is the output of the above code snippet:<\/p>\n<p><span style=\"text-decoration: underline\"><em>Result<\/em><\/span><\/p>\n<pre class=\"brush:bash\">Both strings are not same.\n<\/pre>\n<h3 class=\"wp-block-heading\" id=\"h-2-9-check-the-return-value-of-external-methods\">2.9 Check the return value of external methods<\/h3>\n<p>It is very common in practice to make use of external libraries. These libraries contain methods that return a reference. Make sure that the returned reference is not&nbsp;<code>null<\/code>. Also, consider reading the Javadoc of the method, in order to better understand its functionality and its return values.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-2-10-use-assertions\">2.10 Use Assertions<\/h3>\n<p>Assertions are very useful while testing your code and can be used, in order to avoid executing code snippets that will throw a&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code>. Java Assertions are implemented with the assert keyword and throw an&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/AssertionError.html\">AssertionError<\/a><\/code>.<\/p>\n<p>Notice that you must explicitly enable the assertion flag of the JVM, by executing it with the&nbsp;<code>\u2013ea<\/code>&nbsp;argument. Otherwise, the assertions will be completely ignored.<\/p>\n<p>A sample example using Java assertions is the following:<\/p>\n<pre class=\"brush:java\">public static int getLength(String s) {\n     \/* Ensure that the String is not null. *\/\n     assert (s != null);\n \n     return s.length();\n}\n<\/pre>\n<p>If you execute the above code snippet and pass a null argument to&nbsp;<code>getLength<\/code>, the following error message will appear:<\/p>\n<pre class=\"brush:bash\">Exception in thread \"main\" java.lang.AssertionError\n<\/pre>\n<p>Finally, you can use the&nbsp;<code><a href=\"http:\/\/junit.sourceforge.net\/javadoc\/org\/junit\/Assert.html\">Assert<\/a><\/code>&nbsp;class provided by the&nbsp;<code><a href=\"http:\/\/junit.org\/\">jUnit<\/a><\/code>&nbsp;testing framework.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-2-11-unit-tests\">2.11 Unit Tests<\/h3>\n<p>Unit tests can be extremely useful while testing the functionality and correctness of your code. Devote some time to write a couple tests cases that verify that no&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code>&nbsp;is thrown, while your application\u2019s code undergoes a specific execution flow.<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-3-existing-nullpointerexception-safe-methods\">3. Existing NullPointerException safe methods<\/h2>\n<h3 class=\"wp-block-heading\" id=\"h-3-1-accessing-static-members-or-methods-of-a-class\">3.1 Accessing static members or methods of a class<\/h3>\n<p>When your code attempts to access a static variable or method of a class, even if the object\u2019s reference equals to&nbsp;<code>null<\/code>, the JVM does not throw a&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code>. This is due to the fact that the Java compiler stores the static methods and fields in a special place, during the compilation procedure. Thus, the static fields and methods are not associated with objects, rather with the name of the class.<\/p>\n<p>For example, the following code does not throw a&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code>:<\/p>\n<p><span style=\"text-decoration: underline\"><em>TestStatic.java:<\/em><\/span><\/p>\n<pre class=\"brush:java\">class SampleClass {\n \n     public static void printMessage() {\n          System.out.println(\"Hello from Java Code Geeks!\");\n     }\n}\n \npublic class TestStatic {\n     public static void main(String[] args) {\n          SampleClass sc = null;\n          sc.printMessage();\n     }\n}\n<\/pre>\n<p>Notice, that despite the fact that the instance of the&nbsp;<code>SampleClass<\/code>&nbsp;equals to&nbsp;<code>null<\/code>, the method will be executed properly. However, when it comes to static methods or fields, it is better to access them in a static way, such as&nbsp;<code>SampleClass.printMessage()<\/code>.<\/p>\n<h3 class=\"wp-block-heading\" id=\"h-3-2-the-instanceof-operator\">3.2 The instanceof operator<\/h3>\n<p>The&nbsp;<code>instanceof<\/code>&nbsp;operator can be used, even if the object\u2019s reference equals to&nbsp;<code>null<\/code>. The&nbsp;<code>instanceof<\/code>&nbsp;operator returns false when the reference equals to null and does not throw a&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code>. For example, consider the following code snippet:<\/p>\n<pre class=\"brush:java\">String str = null;\nif(str instanceof String)\n     System.out.println(\"It's an instance of the String class!\");\nelse\n     System.out.println(\"Not an instance of the String class!\");\n<\/pre>\n<p>The result of the execution is, as expected:<\/p>\n<pre class=\"brush:bash\">Not an instance of the String class!\n<\/pre>\n<p>This was a tutorial on how to handle the Java Null Pointer Exception ( java.lang.NullPointerException \u2013&nbsp;<code><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/lang\/NullPointerException.html\">NullPointerException<\/a><\/code> )<\/p>\n<h2 class=\"wp-block-heading\" id=\"h-4-more-articles\">4. More articles<\/h2>\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/try-catch-java-example\/\">Try Catch Java Example<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/java-tutorial-for-beginners\/\">Java Tutorial for Beginners<\/a><\/li>\n<li><a href=\"https:\/\/examples.javacodegeeks.com\/what-is-java-used-for\/\">What is Java used for<\/a><\/li>\n<\/ul>\n<h2 class=\"wp-block-heading\" id=\"h-5-download-the-source-code\">5. Download the Source Code<\/h2>\n<p>This source contains the example code snippets used in this article to illustrate java.lang.NullPointerException Example &#8211; How to handle Java Null Pointer Exception.<\/p>\n<div class=\"download\"><strong>Download<\/strong><br \/>\nYou can download the full source code of this example here: <a href=\"http:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2019\/09\/handling_null_pointer_exception_in_java.zip\"><strong>java.lang.NullPointerException Example &#8211; How to handle Java Null Pointer Exception<\/strong><\/a><\/div>\n<p><strong>Last updated on May 12th, 2021<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this post, we feature a comprehensive example of java.lang.NullPointerException &#8211; Java Null Pointer Exception. In Java, a special&nbsp;null&nbsp;value can be assigned to an object\u2019s reference and denotes that the object is currently pointing to&nbsp;an unknown&nbsp;piece of data. A&nbsp;java.lang.NullPointerException is thrown when an application is trying to use or access an object whose reference equals &hellip;<\/p>\n","protected":false},"author":8,"featured_media":1204,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[118],"tags":[505,263,506,507],"class_list":["post-7653","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-exceptions","tag-apache-commons-lang","tag-featured","tag-null-object-pattern","tag-singleton-pattern"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>java.lang.NullPointerException - Examples Java Code Geeks - 2026<\/title>\n<meta name=\"description\" content=\"Check out our java.lang.NullPointerException Example - How to handle Java Null Pointer Exception. A special null value can be assigned.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"java.lang.NullPointerException - Examples Java Code Geeks - 2026\" \/>\n<meta property=\"og:description\" content=\"Check out our java.lang.NullPointerException Example - How to handle Java Null Pointer Exception. A special null value can be assigned.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/\" \/>\n<meta property=\"og:site_name\" content=\"Examples Java Code Geeks\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/javacodegeeks\" \/>\n<meta property=\"article:author\" content=\"https:\/\/www.facebook.com\/stathis.maneas\" \/>\n<meta property=\"article:published_time\" content=\"2013-12-23T15:41:43+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-07-06T10:33:57+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"150\" \/>\n\t<meta property=\"og:image:height\" content=\"150\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Sotirios-Efstathios Maneas\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:site\" content=\"@javacodegeeks\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Sotirios-Efstathios Maneas\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/\"},\"author\":{\"name\":\"Sotirios-Efstathios Maneas\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/03673b064b32807176478bd144079be1\"},\"headline\":\"java.lang.NullPointerException Example &#8211; How to handle Java Null Pointer Exception (with video)\",\"datePublished\":\"2013-12-23T15:41:43+00:00\",\"dateModified\":\"2022-07-06T10:33:57+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/\"},\"wordCount\":1639,\"commentCount\":6,\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"keywords\":[\"Apache Commons Lang\",\"featured\",\"Null Object Pattern\",\"Singleton Pattern\"],\"articleSection\":[\"exceptions\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/\",\"name\":\"java.lang.NullPointerException - Examples Java Code Geeks - 2026\",\"isPartOf\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"datePublished\":\"2013-12-23T15:41:43+00:00\",\"dateModified\":\"2022-07-06T10:33:57+00:00\",\"description\":\"Check out our java.lang.NullPointerException Example - How to handle Java Null Pointer Exception. A special null value can be assigned.\",\"breadcrumb\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#primaryimage\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg\",\"width\":150,\"height\":150,\"caption\":\"Bipartite Graph\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/examples.javacodegeeks.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Java Development\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/\"},{\"@type\":\"ListItem\",\"position\":3,\"name\":\"Java Basics\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/java-basics\/\"},{\"@type\":\"ListItem\",\"position\":4,\"name\":\"exceptions\",\"item\":\"https:\/\/examples.javacodegeeks.com\/category\/java-development\/java-basics\/exceptions\/\"},{\"@type\":\"ListItem\",\"position\":5,\"name\":\"java.lang.NullPointerException Example &#8211; How to handle Java Null Pointer Exception (with video)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#website\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"name\":\"Java Code Geeks\",\"description\":\"Java Examples and Code Snippets\",\"publisher\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\"},\"alternateName\":\"JCG\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#organization\",\"name\":\"Exelixis Media P.C.\",\"url\":\"https:\/\/examples.javacodegeeks.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png\",\"width\":864,\"height\":246,\"caption\":\"Exelixis Media P.C.\"},\"image\":{\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/javacodegeeks\",\"https:\/\/x.com\/javacodegeeks\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/03673b064b32807176478bd144079be1\",\"name\":\"Sotirios-Efstathios Maneas\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2013\/10\/Stathis-Maneas-96x96.jpg\",\"contentUrl\":\"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2013\/10\/Stathis-Maneas-96x96.jpg\",\"caption\":\"Sotirios-Efstathios Maneas\"},\"description\":\"Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.\",\"sameAs\":[\"https:\/\/www.cs.utoronto.ca\/~smaneas\/\",\"https:\/\/www.facebook.com\/stathis.maneas\",\"https:\/\/linkedin.com\/in\/smaneas\"],\"url\":\"https:\/\/examples.javacodegeeks.com\/author\/stathis-maneas\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"java.lang.NullPointerException - Examples Java Code Geeks - 2026","description":"Check out our java.lang.NullPointerException Example - How to handle Java Null Pointer Exception. A special null value can be assigned.","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:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/","og_locale":"en_US","og_type":"article","og_title":"java.lang.NullPointerException - Examples Java Code Geeks - 2026","og_description":"Check out our java.lang.NullPointerException Example - How to handle Java Null Pointer Exception. A special null value can be assigned.","og_url":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/","og_site_name":"Examples Java Code Geeks","article_publisher":"https:\/\/www.facebook.com\/javacodegeeks","article_author":"https:\/\/www.facebook.com\/stathis.maneas","article_published_time":"2013-12-23T15:41:43+00:00","article_modified_time":"2022-07-06T10:33:57+00:00","og_image":[{"width":150,"height":150,"url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","type":"image\/jpeg"}],"author":"Sotirios-Efstathios Maneas","twitter_card":"summary_large_image","twitter_creator":"@javacodegeeks","twitter_site":"@javacodegeeks","twitter_misc":{"Written by":"Sotirios-Efstathios Maneas","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#article","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/"},"author":{"name":"Sotirios-Efstathios Maneas","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/03673b064b32807176478bd144079be1"},"headline":"java.lang.NullPointerException Example &#8211; How to handle Java Null Pointer Exception (with video)","datePublished":"2013-12-23T15:41:43+00:00","dateModified":"2022-07-06T10:33:57+00:00","mainEntityOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/"},"wordCount":1639,"commentCount":6,"publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","keywords":["Apache Commons Lang","featured","Null Object Pattern","Singleton Pattern"],"articleSection":["exceptions"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/","url":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/","name":"java.lang.NullPointerException - Examples Java Code Geeks - 2026","isPartOf":{"@id":"https:\/\/examples.javacodegeeks.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#primaryimage"},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#primaryimage"},"thumbnailUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","datePublished":"2013-12-23T15:41:43+00:00","dateModified":"2022-07-06T10:33:57+00:00","description":"Check out our java.lang.NullPointerException Example - How to handle Java Null Pointer Exception. A special null value can be assigned.","breadcrumb":{"@id":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#primaryimage","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2012\/12\/java-logo.jpg","width":150,"height":150,"caption":"Bipartite Graph"},{"@type":"BreadcrumbList","@id":"https:\/\/examples.javacodegeeks.com\/java-lang-nullpointerexception-example\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/examples.javacodegeeks.com\/"},{"@type":"ListItem","position":2,"name":"Java Development","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/"},{"@type":"ListItem","position":3,"name":"Java Basics","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/java-basics\/"},{"@type":"ListItem","position":4,"name":"exceptions","item":"https:\/\/examples.javacodegeeks.com\/category\/java-development\/java-basics\/exceptions\/"},{"@type":"ListItem","position":5,"name":"java.lang.NullPointerException Example &#8211; How to handle Java Null Pointer Exception (with video)"}]},{"@type":"WebSite","@id":"https:\/\/examples.javacodegeeks.com\/#website","url":"https:\/\/examples.javacodegeeks.com\/","name":"Java Code Geeks","description":"Java Examples and Code Snippets","publisher":{"@id":"https:\/\/examples.javacodegeeks.com\/#organization"},"alternateName":"JCG","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/examples.javacodegeeks.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/examples.javacodegeeks.com\/#organization","name":"Exelixis Media P.C.","url":"https:\/\/examples.javacodegeeks.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2022\/06\/exelixis-logo.png","width":864,"height":246,"caption":"Exelixis Media P.C."},"image":{"@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/javacodegeeks","https:\/\/x.com\/javacodegeeks"]},{"@type":"Person","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/03673b064b32807176478bd144079be1","name":"Sotirios-Efstathios Maneas","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/examples.javacodegeeks.com\/#\/schema\/person\/image\/","url":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2013\/10\/Stathis-Maneas-96x96.jpg","contentUrl":"https:\/\/examples.javacodegeeks.com\/wp-content\/uploads\/2013\/10\/Stathis-Maneas-96x96.jpg","caption":"Sotirios-Efstathios Maneas"},"description":"Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.","sameAs":["https:\/\/www.cs.utoronto.ca\/~smaneas\/","https:\/\/www.facebook.com\/stathis.maneas","https:\/\/linkedin.com\/in\/smaneas"],"url":"https:\/\/examples.javacodegeeks.com\/author\/stathis-maneas\/"}]}},"_links":{"self":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/7653","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/users\/8"}],"replies":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/comments?post=7653"}],"version-history":[{"count":0,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/posts\/7653\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media\/1204"}],"wp:attachment":[{"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/media?parent=7653"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/categories?post=7653"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/examples.javacodegeeks.com\/wp-json\/wp\/v2\/tags?post=7653"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}