What is the solution to all present, past and future NullPointerException errors?


I have my Java program and I get a NullPointerException and I have seen other questions but they are from people with other programs and it does not work for my program and I want to leave here the 2,000 lines of my program so that you solve the problem but the people will not leave me.

Look, my program is like this

  Object a = null;
  // 500 líneas de código
  // Dentro de un bucle, dentro de un if, dentro de un for...
  a = algunaFuncionDeMilLineasQueNoTeVoyAMostrar(
  // Cerrando for, cerrando if, cerrando bucle.
  // Otras 500 líneas de código
  // Una de estas líneas lanza el NPE, pero no te diré cuál.

What is wrong? Why is not there a solution that works for all NullPointerException (NPE) if they occur so often?

asked by SJuan76 08.01.2017 в 19:54

6 answers


The solution is (drum roll) ...

Do not use methods or properties of a variable or expression that is null

If you have a line:


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");
    case 2:
      myObj = new Integer(1);

    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.

answered by 25.09.2017 / 17:09

If you suspect that the variable has a null and will give a NullPointerException error, solve it by adding a try-catch block and recover the error. You can give your objects a new Object and upload the null as a string to your application and you can see which object is the one that breaks the flow of your program.

You can also read the warnings in the code, they help a lot.

I hope it has served you.

answered by 22.05.2017 в 23:16

What good afternoon, of course there is a solution to the management of the NPE and it is not necessarily the exception handling, I recommend that you use the Null Object Pattern design , this will make your code is more robust and you will have control of this type of errors, thus preventing the program from being interrupted at runtime.

I leave you the UML diagram:

The implementation is really simple. I recommend you do not validate object.algo.algo! = null and do not abuse the generalized try / catch because that will not solve your problem they will only be controlling it but the underlying problem will continue to exist.

Greetings !!!

answered by 04.11.2017 в 01:27

Part of your problem is probably that of the funciondeMilLineas you are doing very long and very convoluted functions in which it is easy to be wrong. A simple general rule about how long a function should be is that it can be seen on a screen. That's about 40 lines on my monitor. You can play with the size of the letter, but more or less that is the length.

It is not easy to learn how to divide the code into functions. What I've read about the topic I liked the most was a book by Robert C. Martin called Clean Code and has an entire chapter on functions. There what it says is:


A function should do only one thing

It obviously costs a bit to understand what this means and apply it in practice. But I think it's worth learning that before doing programs that work but then they are too convoluted to extend them.

The NullPointerException is that you have not initialized any Java reference. Simplifying it to the beast is that you need some new somewhere.

PS: If you really get to a function of a thousand lines do not doubt that it is wrong. That has to be divided.

answered by 08.01.2017 в 20:56

You can implement a try{}catch(NullPointerException){} because as it says catch all the fields that are null or make sure they are not null at the time of calling them. You can implement a method that receives the object and verify that it is not null.

public boolean isnull(Object a){

 return true;
 return false

or better make sure at the time of programming that it is already contains the reference or that it is initialized.

answered by 13.09.2017 в 21:19

If I could contribute something, which I do not believe, because they have responded quite well above (now I will give the vote) I would add:

-If it is a parameter, you must verify it before using it. -If it is a result, use optional


public Optional<String> unMetodoCualquiera( String parametro ) {
  return Optional.ofNullable(...);
answered by 20.04.2018 в 19:16