The solution is (drum roll) ...
Do not use methods or properties of a variable or expression that is null
If you have a line:
p.hacerAlgo();
and it throws you an NPE, is that when you execute it p
is worth null
. Make sure you have a non-null value before running the line.
That's it ...
You do not have to repeat the same question a million times, even if the program is different
It's clear, right? As promised, resolved forever and ever.
And now is when someone protests: "But that does not help me with my problem that I get a NullPointerException in my program that I write here 1 "?
The answer: If there is a NullPointerException, your problem is not the NullPointerException.
It is the responsibility of a programmer to know how your program works and how the data is organized. It is not the kind of question that can be downloaded to StackOverflow. If you have an NPE, you are with one (or more) of these cases:
-
You are bound by the logic of the program and do not follow the path that you thought. Solution: Carry out debug your program
The typical case is to say "in this method a
can be 1 or 2" and do
Object myObj = null;
switch (a) {
case 1:
myOjb = new String("Hola");
break;
case 2:
myObj = new Integer(1);
}
myObj.toString();
Your problem is that a
is worth something that you did not expect, together with the fact that you do not program defensively and do not control the values. Debug your program to solve the value of a
, add a default
that throws an exception when the value is unexpected.
-
You have such a complicated method that you do not know when values are assigned to the reference. Modify your program so that it is easy to read and understand. Do not do like the old elbonios who said "Writing is easy, we hope to learn to read someday". If you want to check if your program works how you expect, use a debugging tool or generate log messages so that you can verify its operation. If you need someone from the Internet to explain how your program works, consider another profession.
-
You have a problem with the API. You have followed all the steps mentioned above, and in the end you have found that the cause of the origin is that you are calling java.util.Collections.toArray()
and it returns a value null
. Check the documentation of the method, check the parameters you pass, etc. If you still can not find the solution, ¡Congratulations !!!! Now you have a question that is valid for SO ("Why java.util.Collections.toArray () returns me null ? ")
-
You have a vector that you initialized in some way, but you never initialized it internally. do this tipo1 vector[] = new tipo1[n];
It does not imply that the vector magically filled with objects of type1. You must make a New type1 for each position of the vector
1 Followed by a thousand lines of code, and of course without even indicating in which line the NPE is launched.