Pages

1.22.2012

java.lang.NullPointerException: How to resolve

Exception in thread "main" java.lang.NullPointerException is one of the common problems and Java error that you will face when developing Java or Java EE applications. This Java Exception has been around since early JDK days e.g. JDK 1.0.

Most of you probably have seen and resolve this problem multiple times so this article is mainly dedicated for individuals new in Java or interested to revisit this Java Exception.

java.lang.NullPointerException: Overview

NullPointerException is a runtime Exception thrown by the JVM when your application code, other referenced API(s) or middleware (Weblogic, WAS, JBoss...) encounters the following conditions:

-        Attempting to invoke an instance method of a null object
-        Attempting to access or modify a particular field of a null object
-        Attempting to obtain the length of such null object as an array

java.lang.NullPointerException: Sample Java program

** A YouTube tutorial video is now available.

It is always best to learn with examples and sample Java programs. The program below is a very simple Java program generating a java.lang.NullPointerException. Please simply copy/paste and run the program with the IDE of your choice (Eclipse IDE was used for this example).

package org.ph.java.courses;

/**
 * NullPointerExceptionSampleProgram
 * @author Pierre-Hugues Charbonneau
 *
 */
public class NullPointerExceptionSampleProgram {
      
       private String field1 = null;
       private String field2 = null;   
      
       public String getField1() {
             return field1;
       }

       public void setField1(String field1) {
             this.field1 = field1;
       }

       public String getField2() {
             return field2;
       }

       public void setField2(String field2) {
             this.field2 = field2;
       }

       /**
        * @param args
        */
       public static void main(String[] args) {
            
             try {
                    // Create a fresh object instance
                    NullPointerExceptionSampleProgram objectInstance =
                                 new NullPointerExceptionSampleProgram();                   
                    // Initialize field1...
                    objectInstance.setField1("field1Value");
                   
                    // reset our object instance to null
                    objectInstance = null;
                   
                    // Now initialize field2...BOOM! >> NullPointerException!
                    objectInstance.setField2("field1Value2");
            
             } catch (Throwable any) {
                    System.out.println("Java ERROR: "+any);
                    any.printStackTrace();
             }
            
       }

}

If you run the program as is, you will see the output as per below:

java.lang.NullPointerException
       at org.ph.java.courses.NullPointerExceptionSampleProgram.main
(NullPointerExceptionSampleProgram.java:47)

Java ERROR: java.lang.NullPointerException

As you can see in our example, the NullPointerException is thrown when attempting to execute the setField2() method against our objectInstance which is now null.

The JVM will typically show you the line of code (line 47 in this example) where the NullPointerException is triggered. This is critical data since it allows you to trace back the problem in your application Java code at this particular line of code of the affected Java class.

java.lang.NullPointerException: Resolution strategies

Now that you understand this problem, it is now time to resolve it. Complexity of the resolution will depend of the context of your problem since NullPointerException can be a problem by itself or simply a symptom of another problem (no data returned from a Web Service call etc.). Regardless of the context & root cause, you must shield your Java code and add proper error handling and null check validations when applicable:

-        Review the java.lang.NullPointerException Stack Trace and determine where the Exception is triggered (your application code, third part API, middleware software such as Weblogic etc.) and extract the line #
-        If problem is at your application code then a code walkthrough will be required. If problem is found from third party API and / or middleware, my recommendation is to first review your referenced code and determine if it could be indirectly be the source of the problem e.g. passing a null value to a third part API method etc.
-        If problem found within your application code, then attempt to determine which Object instance is null and causing the problem. You will need to modify your code in order to add proper null check validations and proper logging so you can understand the source of the null value as well

Now back at our example, a simple validation and logging can be added as per below:

** Please note that logging should be done via standard logging framework such as Log4J **

// Now Initialize field2 but only if objectInstance is not null
if (objectInstance != null) {
objectInstance.setField2("field1Value2");
} else{
       System.out.println("objectInstance is null, do not attempt to initialize field2");
}

Conclusion and best practices

Best practices include:

-        Add proper null check validations before attempting to use an object Instance method e.g. if (objectInstance != null) { objectInstance.method(); }
-        When a null object is found, please add proper logging so you can pinpoint the root cause / source of the null value
-        Avoid too many object instance method calls on a single line as it will increase diagnostic complexity in the event of a NullPointerException e.g. avoid calls like this below unless properly checked for null prior to the call:
objectInstance.method(objectInstance2.getData(), objectInstance3.getData(),objectInstance4.getData());

I hope this article has helped you to understand what is null in Java.
Please feel free to add any comment or question if you are still struggling with a java.lang.NullPointerException problem.

46 comments:

  1. Hi P-H, thanks for another good post. Just like NoClassDefFoundError is biggest nightmare of experienced programmer, NPE is biggest nemesis for beginners, its way more frustrating until you get hold of it. I have shared some common cause of NullPointerException in Java, which seems to be good compliment to this post and help people to get around of NPE.

    ReplyDelete
  2. Hi P-H...., ur article really helped me alot.

    thanks alot

    ReplyDelete
  3. Many Thanks. I've been tearing my hair out for days!
    Hopefully will now be able to pinpoint the problem.

    ReplyDelete
  4. Thanks for your comments.

    Please feel free to share your problem case if you are still struggling.

    P-H

    ReplyDelete
  5. Hi Anonymous,

    I will review the code but can you please also provide the StackTrace of the NullPointerException that you are getting e.g. we need to understand which line of code is triggering this error.

    Thanks.
    P-H

    ReplyDelete
  6. I'm trying to fill out an application for a school in Korea. When I try to save the page I get the java.lang.NullPointerException message being discussed on this page. I tried both Firefox and Safari. Same message. I'm not programmer and the conversation here is beyond me. My only question is, is this something that can be fixed on my end or is this a problem originating on the application end? Thank you, Maria

    ReplyDelete
  7. Hi Mario,

    If you are seing a java.lang.NullPointerException from your browser after filling a form then problem is very likely on the hosting Java application.

    Please contact the support team of this school in Korea so they can investigate their server logs.

    Thanks.
    P-H

    ReplyDelete
  8. I found following error when i am trying to open properties of ARETU of Node-B (Ericssson 3G BTS)
    Exception: RuntimeException
    java.lang.NullPointerException
    ava.lang.RuntimeException: java.lang.NullPointerException
    at se.ericsson.cello.support.gui.guilib.infra.ApplicationManager.runApplication(Unknown Source)
    at se.ericsson.cello.support.gui.LaunchExternalApplication.run(Unknown Source)
    Caused by: java.lang.NullPointerException
    at se.ericsson.security.launcher.cache.Cache.getFileFromURL(Unknown Source)
    at se.ericsson.security.launcher.cache.Cache.getFile(Unknown Source)
    at se.ericsson.security.launcher.cache.Cache.prepareApplication(Unknown Source)
    at se.ericsson.security.launcher.Launcher.runApplication(Unknown Source)
    ... 2 more

    ReplyDelete
  9. Thanks P H

    Nice article.

    ReplyDelete
  10. Hi Anonymous,

    Do you have the NullPointerException stack trace so we can see at which line of code your are getting your NPE?

    The above code appears to be non managing properly the creation and close of the Statement object but first let's review your full stack trace and line of code where NPE is triggered.

    Thanks.
    P-H

    ReplyDelete
  11. I have been unable to connect with the 4shared site for over a week. I get the following error message. I have read the above info but don't know how to run the fix noted in the top box. I would appreciate your help


    HTTP Status 500 -

    --------------------------------------------------------------------------------

    type Exception report

    message

    description The server encountered an internal error () that prevented it from fulfilling this request.

    exception

    java.lang.NullPointerException


    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.16 logs.


    --------------------------------------------------------------------------------

    Apache Tomcat/6.0.16

    ReplyDelete
  12. Hi anonymous,

    I assume you get the error when you attempt to connect through the 4shared Internet site e.g. file sharing provider. Is that correct?

    Thanks.
    P-H

    ReplyDelete
  13. Thanks so much for your response!

    Yes -- I have a free account there for downloading files. I cannot get to the download page that comes just before the sign in page.

    I can get to it on my netbook but not my primary computer.

    ReplyDelete
  14. Hi anonymous,

    The error you get is server side from the 4shared site. This is not something you can fix on your side (client). I recommend 2 actions at this point:

    1) Clear your cache etc, or try with more browser types & versions from your primary computer
    2) Contact 4shared technical support and provide them the error. They may be able to look at their Apache Tomcat server logs and see what is the problem with your account

    Regards,
    P-H

    ReplyDelete
  15. Many thanks for this information & suggestions.
    I have cleared the cache several times & have installed Firefox & I can get to the sign in page but it stalls & doesn't move forward.
    I will contact their support & hopefully get the issue resolved.

    I appreciate your help very much!
    Thanks again

    ReplyDelete
  16. Sorry but this is way over my head, all I know is that when I am trying to down load from Google Cloud on to My Samsung Tablet I get java.lang.NullPointerException.

    The system worked up until yesterday any clear basic help you can give would be appreciated

    ReplyDelete
  17. Hi Anonymous,

    Do you have a snapshot of the java.lang.NullPointerException from your Samsung tablet that you can share? Do you see a list of stack trace lines or just this one liner java.lang.NullPointerException?

    Thanks.
    P-H

    ReplyDelete
  18. Hi Rekha,

    The NPE you are getting is because your pstatement object is null, causing failure when you are attempting to close it.

    Please add logging and understand why your pstatement is null, you are likely getting an Exceptin when executing this line:
    pstatement = connection.prepareStatement(queryString);

    Best practices also include to validate JDBC related objects for null before attempting to close e.g. replace your code closure by this:

    finally {

    if (pstatement != null)pstatement.close();
    if (connection != null)connection.close();

    }

    ReplyDelete
  19. I used a scanner method to scan in a string and the toCharArray method but it gives me this error:
    java.lang.NullPointerException
    at SuperAnagram.(SuperAnagram.java:4)
    at SuperAnTester.main(SuperAnTester.java:10)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

    ReplyDelete
  20. Hi Jake,

    Can you please share the Java code from the class: SuperAnagram.java
    We need to look at line #4 in order to see which variable or object is null.

    Thanks.
    P-H

    ReplyDelete
  21. Hi P-H,

    I am using Oracle SQL Developer to pull out tables for my client. It gives me Failure-java.lang.NullPointerException. I am not a programmer and dont understand Java. Please help me out.

    Thanks,
    Aditya

    ReplyDelete
  22. Hi Aditya,

    Can you please share the entire Exception stack trace. You will likely see this from the SQL Developer logs.

    Thanks.
    P-H

    ReplyDelete
  23. Hi Pierre,

    This is what it says.

    java.lang.NullPointerException
    at oracle.dbtools.raptor.conntypes.RaptorClassLoader.findClassLoader(RaptorClassLoader.java:48)
    at oracle.dbtools.raptor.conntypes.RaptorConnectionWrapper.createConnectionImpl(RaptorConnectionWrapper.java:202)
    at oracle.dbtools.raptor.conntypes.RaptorConnectionWrapper.createConnection(RaptorConnectionWrapper.java:160)
    at oracle.dbtools.raptor.conntypes.RaptorConnectionWrapper.getJdbcConnection(RaptorConnectionWrapper.java:191)
    at oracle.dbtools.raptor.conntypes.RaptorConnectionWrapper.getPresentation(RaptorConnectionWrapper.java:66)
    at oracle.dbtools.raptor.utils.Connections$ConnectionInfo.createConnection(Connections.java:781)
    at oracle.dbtools.raptor.utils.Connections$ConnectionInfo$ConnectRunnable.doWork(Connections.java:654)
    at oracle.ide.dialogs.ProgressRunnable.run(ProgressRunnable.java:159)
    at oracle.ide.dialogs.ProgressBar.run(ProgressBar.java:553)
    at java.lang.Thread.run(Thread.java:595)

    Thanks,
    Aditya

    ReplyDelete
  24. Hi I recommend that you review this Oracle forum thread as it describes the same problem with possible solutions. You may also want to explore to install the latest version of SQL Developer.

    https://kr.forums.oracle.com/forums/thread.jspa?threadID=863466

    Thanks.
    P-H

    ReplyDelete
  25. Hi Pierre,

    Thanks for the help, I realized the problem was because of improper installation of Java.

    Thanks,
    Aditya

    ReplyDelete
  26. Thanks Scythe for posting back the solution to your problem.

    Happy to help.

    Regards,
    P-H

    ReplyDelete
  27. hi,
    i m looking for .mdl to .ecore conversion.
    will u help me out with brief steps.

    ReplyDelete
  28. hey can you help me with a NULLPOINTER exception problem

    ReplyDelete
  29. Hi Sakthi,

    Please post the full NullPointerException error and stacktrace that you are getting and let me know under which context you are getting this e.g. Java programming or using software/game?

    Thanks.
    P-H

    ReplyDelete
  30. type Exception report

    message java.lang.NullPointerException

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: java.lang.NullPointerException
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)


    root cause

    java.lang.NullPointerException
    org.apache.jsp.index2_jsp._jspService(index2_jsp.java:75)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)


    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.36 logs.


    --------------------------------------------------------------------------------

    Apache Tomcat/6.0.36

    ReplyDelete
  31. hello.
    i have a problem.
    how i want to call text field data from other form?
    my situation is,
    i want to make reservation button for reservation form. when user click reservation, their data will appear on the text fields.
    the code for the button will refer to Username text field in the Login Form. How i want to call the data?

    ReplyDelete
  32. Hi,author
    I've encounter the same problem..If I post to u my codes,how long will you take to pinpoint and correct my mistakes? I don't think my code is a difficult one, but I'm a complete beginner in java, so I'm having hard time finding which part did I done wrong..

    ReplyDelete
  33. Hi jhawahar,

    Can you please also provide the full Exception stack trace when you get the error and exact line of code where the NPE is triggered?

    Thanks.
    P-H

    ReplyDelete
  34. Hi Pierre,

    Could you please help me to solve the problem below?:

    java.lang.NullPointerException
    at shared.Money.subtract(Money.java:91)
    at shared.AuctionInfo.getCurrentBid(AuctionInfo.java:202)
    at gui.veiling.createAuction(veiling.java:54)
    at gui.veiling.(veiling.java:39)
    at gui.veilinglijst.updateList(veilinglijst.java:294)
    at source.Client.KickList(Client.java:157)
    at source.Client$1.run(Client.java:189)

    ReplyDelete
  35. Hi Claude,

    We can see that the NPE is triggered within the following code:

    at shared.Money.subtract(Money.java:91) e.g. Java class: Money, at line 91.

    Do you have access to the source code so you can identify what potential object is null?

    Regards,
    P-H

    ReplyDelete
  36. Hi Pierre,

    Thanks for your reply. Yes I have access to the source code but the application is very complex. I cannot see where the object is null.
    Do you have a TeamViewer so that I share my code with you?

    Thanks again.

    Claude

    ReplyDelete
  37. Hi Claude,

    You can email me a snippet of your code (Money.java) at: phcharbonneau@hotmail.com

    ReplyDelete
  38. Hi Pierre-Hugues,

    I just mail you the Money.java code as requested.

    Regards,
    Claude

    ReplyDelete
  39. I use bukkit server and it says it when every I open it java.null.pointerexception please help!

    Sincerely, Anonymous

    ReplyDelete
  40. Hi anonymous,

    Do you have the source code of the Java class throwing the java.lang.NullPointerException?

    ReplyDelete
  41. Thank you P-H.

    The article was helpful to me.

    Regards
    Ahmed

    ReplyDelete
  42. Thanks alot your article really helped me out.
    All the best man

    ReplyDelete
  43. Hi, i'm also having some problems with Java.Lang.Nullpointerexception as well. I'm trying to log into NKO to do some work on my ASUS Transformer tablet but the page that keeps coming up is this

    type Exception report

    message java.lang.NullPointerException

    description The server encountered an internal error that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: java.lang.NullPointerException
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    root cause

    java.lang.NullPointerException
    org.apache.jsp.index2_jsp._jspService(index2_jsp.java:75)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.37 logs.
    Please if you can help me that would be wonderful, I really don't want to have to return my computer and cac card due to this code that is seeminly fixable.

    ReplyDelete
  44. Hi,
    I am trying to access a jsp page by redirecting form the servlet. i am using weblogic server.
    I am newbie to weblogic.
    I am getting the Internal server error .
    Below is the error it displayed.




    Error 500--Internal Server Error
    java.lang.NullPointerException
    at jsp_servlet.__eprofileupdate._jspService(__eprofileupdate.java:205)
    at weblogic.servlet.jsp.JspBase.service(JspBase.java:34)
    at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
    at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:301)
    at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:184)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3732)
    at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3696)
    at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
    at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
    at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2273)
    at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2179)
    at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1490)
    at weblogic.work.SelfTuningWorkManagerImpl$WorkAdapterImpl.run(SelfTuningWorkManagerImpl.java:545)
    at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
    at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)



    Please help me out in resolving this .

    Thanks in advance.

    ReplyDelete
  45. i don't get it!!!!!! very confusing :(

    ReplyDelete
  46. Hi,
    I am trying to access different websites which requires java to use tools but i am facing this issue. Since i am not a programmer, this solution is beyond me. Just need a simple solution how can i resolve this.

    Thanks..!!

    ReplyDelete