What is null pointer exception
These are the most common, but other ways are listed on the NullPointerException javadoc page. Probably the quickest example code I could come up with to illustrate a NullPointerException would be:.
On the first line inside main , I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it.
This results in a NullPointerException because there is no code to execute in the location that the reference is pointing. This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere , which is subtly different than pointing to a location that happens to be invalid. A good place to start is the JavaDocs. They have this covered:.
Thrown when an application attempts to use null in a case where an object is required. These include:. Applications should throw instances of this class to indicate other illegal uses of the null object. It is also the case that if you attempt to use a null reference with synchronized , that will also throw this exception, per the JLS :.
So you have a NullPointerException. How do you fix it? Let's take a simple example which throws a NullPointerException :. The first step is identifying exactly which values are causing the exception.
For this, we need to do some debugging. It's important to learn to read a stacktrace. This will show you where the exception was thrown:. Here, we see that the exception is thrown on line 13 in the printString method. Look at the line and check which values are null by adding logging statements or using a debugger. We find out that s is null, and calling the length method on it throws the exception.
We can see that the program stops throwing the exception when s. Next check where this value comes from. By following the callers of the method, we see that s is passed in with printString name in the print method, and this. Where is this. In the setName String method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.
This is enough to give us a solution: add a call to printer. The variable can have a default value and setName can prevent it being set to null :. Either the print or printString method can check for null , for example:. If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far.
At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. As you should know, Java types are divided into primitive types boolean , int , etc. Reference types in Java allow you to use the special value null which is the Java way of saying "no object".
A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:. There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:.
First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. Some IDEs may warn your program will always throw an exception Second observation: when I run the program, it outputs two lines of "gobbledy-gook". That's not gobbledy-gook. It is a stacktrace Note that in a more complicated example, there will be lots of lines in the NPE stack trace.
But you can be sure that the second line the first "at" line will tell you where the NPE was thrown 1. In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE.
See also: What is a stack trace, and how can I use it to debug my application errors? This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation. Let's illustrate with the simple example above first. We start by looking at the line that the stack trace has told us is where the NPE happened:. In fact, there is only one way: it can only happen if foo has the value null.
We then try to run the length method on null and Well, if that happened, the stack trace would look different. The first "at" line would say that the exception was thrown in some line in the java.
String class and line 4 of Test. So where did that null come from? In this case, it is obvious, and it is obvious what we need to do to fix it. Assign a non-null value to foo. OK, so let's try a slightly more tricky example. This will require some logical deduction. Next, we need to figure out which of those scenarios explains what is actually happening.
We will start by exploring the first one:. As a rule of thumb, check that before any variable is used, it is initialized with an object. If you know the line of code that is causing your NullPointer and believe your logic is correct as well, you can wrap the section of code in a try-catch block, and define the behavior for when a Null Pointer is caught.
This is how such a set-up will look like:. This happens in situations where a certain reference variable may or may not contain null. More often than not, remote API responses, device interface responses are prone to this scenario.
Depending upon the availability of a result or hardware, the response variable may or may not point to an instantiated object. Using safety checks is best-suited to handle these situations. This method is similar to the try-catch method. The biggest difference between the two methods is the scope of checks that they do. The if method checks the myVar variable only for null values, while the try-catch block catches any and all variables that are null.
However, if there is more than one variable that may be null, it is better to go with a try-catch block for simplicity. This article took a look at what Null Pointer Exception is in Java, and how this error occurs. We also looked at a piece of code that will cause a Null Pointer Exception to understand how Null Pointers are created in real-life situations. Finally, we set down to identify some of the top ways to fix a Null Pointer Exception and ended our discussion by contrasting between two methods of fixing NPEs.
If you are looking to write Java programs, a Null Pointer Exception is one of the essential bugs that you must know how to fix. This makes the exception one of the trickiest problems to identify and fix. A quick reference for fixing the issue like this article is bound to make your experience smoother. About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.
Along with writing, he has also worked in software development roles with several start-ups and corporations alike. He joined the Career Karma team in January NullPointerException is thrown when an application attempts to use null in a case where an object is required. These include:. Applications should throw instances of this class to indicate other illegal uses of the null object. I can list out some more reasons of NullPointerException from here :. It is because of wrong programming practice.
You have taken so many precautions to avoid NullPointerException but still you got sometimes. You can easily track reference variable which is reason behind exception. You can just backtrack from there. React Native. Python Design Patterns.
Python Pillow. Python Turtle. Verbal Ability. Interview Questions. Company Questions. Artificial Intelligence. Cloud Computing. Data Science. Angular 7. Machine Learning. Data Structures. Operating System. Computer Network. Compiler Design. Computer Organization.
0コメント