Java – What is NullPointerException and what are the main causes?

The NullPointerException is released when an attempt is made to use that null as if it were an object. That is, if you try to manipulate an object's properties, fields, attributes, or methods without having that object.

The same concept exists in many other programming languages. For example, in C # there is NullReferenceException, Try one in JavaScript null wrongly produced one TypeError, Manipulate as well None erroneously generated in Python AttributeError,

The rest of this answer relates to Java, as indicated in the question. In the other programming languages, what usually happens is very similar to what is described below.


In the special case of Java, the NullPointerException is released in the following situations:

  1. An attempt is made to access a field of an instance that is referenced null,

    Pessoa p = null;
    String nome = p.nome; // <-- NullPointerException aqui.
    
  2. An attempt is made to access a method of an instance whose reference is null,

    Pessoa p = null;
    String nome = p.getNome(); // <-- NullPointerException aqui.
    
  3. Try to use it autounboxing of null, This is especially a prank for beginners in Java.

    Integer x = null;
    int z = x; // <-- NullPointerException aqui.
    

    Another example:

    Integer x = null;
    int z = x + 5; // <-- NullPointerException aqui.
    
  4. Start the NullPointerException direct (obviously).

    throw new NullPointerException();
    
  5. Try to start null as an exception.

    Exception x = null;
    throw x; // <-- NullPointerException aqui.
    
  6. Try to access the size of a variable array that is worth it null,

    String() x = null;
    int tamanho = x.length; // <-- NullPointerException aqui.
    
  7. Try to access an element of a variable array that is worth it null,

    String() x = null;
    String y = x(5); // <-- NullPointerException aqui.
    
  8. Try to iterate null with the syntax of for each,

    String() x = null;
    for (String y : x) { // <-- NullPointerException aqui.
        // ...
    }
    
  9. Try to synchronize (with block synchronized) in null,

    Object x = null;
    synchronized (x) { // <-- NullPointerException aqui.
        // ...
    }
    
  10. Try to get a method reference from null:

    Pessoa p = null;
    Supplier f = p::toString; // <-- NullPointerException aqui.
    

The following situations NO root cause NullPointerExceptionAt least not directly:

  1. To assign null à Object type variables.

    String x = null;
    
  2. To assign null to primitive variables. That doesn't compile, so there isn't NullPointerException 🙂

    int x = null; // Erro de compilação!
    
  3. passport null as parameters of methods or constructors.

    System.out.println(null); // Ok.
    String mensagem = JOptionPane.showInputDialog(null); // Ok.
    JPanel panel = new JPanel(null); // Ok.
    
  4. return null or get null as a return of a method.

    public String getXpto() {
        return null;
    }
    
    public void algumMetodo() {
        String xpto = getXpto(); // Ok. Recebe null.
    }
    
  5. Set the value null in one array or read the value null from a array,

    String() array = new String() {"a", "b", "c"};
    array(1) = null;
    String valor = array(1); // Ok. Recebe null.
    
  6. passport null as a parameter varargs,

    private void metodo(String... parametros) {
        System.out.println(parametros);
    }
    
    private void outroMetodo() {
        // Não dá NullPointerException.
        // Passa como parâmetro um array com um único elemento que é null.
        metodo(null);
    
        // Não dá NullPointerException.
        // Passa como parâmetro um array com dois elementos null.
        metodo(null, null);
    
        // Não dá NullPointerException.
        // Passa como parâmetro null.
        metodo((String()) null);
    }
    
  7. Iterate one array or Collection with elements null,

    String() x = new String() {"a", "b", null, "c"};
    for (String z : x) {
        System.out.println(z);
    }
    

    While this is valid and sometimes even useful, it is important to remember that this situation is still very inviting for any eventuality NullPointerExceptions, since the loop variable is not normally expected to be null:

    String() x = new String() {"a", "b", null, "c"};
    for (String z : x) {
        System.out.println(z.length()); // <-- NullPointerException aqui.
    }
    
  8. Access a static field or method using a reference null, This is a catch of the Java language, because in this case only the type of the variable and not the value is important.

    Integer t = null;
    t.parseInt("123"); // Pegadinha: t é null, mas isso NÃO DÁ NullPointerException!
    System s = null;
    Object x = s.out; // Não dá NullPointerException!
    

    It is also important to note that using a variable to access a static method is bad programming practice because it confuses the code with the unnecessary use of a variable. Do not do it.

  9. Try to use an uninitialized or possibly uninitialized local variable. This leads to a compilation error NullPointerException,

    Pessoa p;
    p.setNome("Maria"); // Erro de compilação, a variável p não foi inicializada.
    
    Pessoa q;
    if (x > y) q = new Pessoa(); // Pode inicializar ou não, dependendo da condição do if.
    
    // Erro de compilação, a variável q possivelmente não foi inicializada.
    q.setNome("Maria");
    

    It is noteworthy that this rule only applies to local variables within methods and constructors. she NO applies to object fields and static variables.

  10. Remember the reference this it will never be null, So one NullPointerException is never caused by trying to manipulate fields and call methods on the object this,

  11. A builder never returns null, So if a result of a constructor call is assigned to a variable, it is guaranteed not to be the case null, Using the example of the following code, it is therefore impossible for the variable p receive null, regardless of what happens in the builder.

    Pessoa p = new Pessoa();
    
  12. The operator instanceof always results false when testing with nulland never throws NullPointerException, Hence if it results truethe tested value is guaranteed not to be zero.

    Animal p = ...;
    if (p instanceof Cachorro) {
        // Se entrar aqui, além de sabermos que p é instância de Cachorro,
        // também sabemos que p não é null.
    }
    
  13. occupations never occupy NullPointerExceptions (but can let go ClassCastExceptions). especially the occupation performed with the value null will always be successful.

    Animal a = null;
    
    // Recebe null. Não lança NullPointerException e nem ClassCastException.
    Cachorro c = (Cachorro) a;
    
  14. Some think that access to one array if the index is invalid a NullPointerException, That's not true. The exception raised in this case is ArrayIndexOutOfBoundsException, Attempts are also made to access the characters of a String in invalid positions also does not cause a NullPointerException and in this case the exception will be StringIndexOutOfBoundsException,

  15. Try to chain null to one String,

    String x = "a" + null + "b"; // Recebe "anullb". Não dá NullPointerException.
    

Almost all cases in which a NullPointerException This is due to a programming error (and for this reason, it almost never makes sense to try to deal with it). So when you get one NullPointerException, You (or someone else) probably did something wrong in the code. For this reason, to protect against NullPointerExceptionThe important thing is to examine the logic of your program to ensure that you never get into a case where a NullPointerException can be started as shown in the situations above at the beginning of this answer (and with the counter examples above too). Your main weapon against this kind of mistake is that if:

if (x == null) {
    // Faz alguma coisa. Não utiliza o x aqui.
} else {
    // Pode utilizar o x seguramente.
}

It is also valid to provide methods (and constructors) with a guard to protect themselves from zero references from "outside" if, This does not lead to programming errors with references. null will disappear, but it will manifest them closer to their origin, making them easier to identify and therefore easier to track and correct. It also makes it easier for you to ensure that your method is error-free, as it eliminates a number of possible programming errors and gives you the guarantee that there will be no strange side effects. only halfway through the demolition NullPointerException, The idea is that if that null is misused (which is a programming error), therefore the programming error is not the responsibility of your method, but of the invalid caller. Here is a simple example:

public void cadastrarNome(String nome) {
    if (nome == null) throw new NullPointerException("Não pode cadastrar um nome nulo.");
    // ... Resto do método.
}     

Or you can use another exception:

public void cadastrarNome(String nome) {
    if (nome == null) {
        throw new IllegalArgumentException("Não pode cadastrar um nome nulo.");
    }
    // ... Resto do método.
}

This is not just limited to the parameter check:

public double somarParcelas() {
    if (parcela1 == null || parcela2 == null) {
        throw new IllegalStateException("Nem todas as parcelas foram adquiridas");
    }
    // ... Resto do método.
}

Another way to implement these guards is to use Objects.requireNonNull(), This method starts a NullPointerException if received as a parameter null:

public void cadastrarNome(String nome) {
    Objects.requireNonNull(nome, "Não pode cadastrar um nome nulo.");
    // ... Resto do método.
}

public double somarParcelas() {
    Objects.requireNonNull(parcela1, "A primeira parcela ainda não foi adquirida.");
    Objects.requireNonNull(parcela2, "A segunda parcela ainda não foi adquirida.");
    // ... Resto do método.
}

It is also valid to encapsulate your references with the class. java.util.Optional:

String x = ...;
Optional opt = Optional.ofNullable(x);
// Neste ponto, opt nunca será nulo, e portanto pode ser
// sempre utilizado seguramente (embora o conteúdo dele possa ser nulo).

As well as protecting yourself from it nullFrom the outside with the guards shown above, it is also important not to spread any values nulls if you can avoid this. For this reason, it is also good to avoid returning home nulls in methods that return something that is "empty", "not initialized", "not applicable", "not available" or "not found". In these cases you can do the following:

  • If your method returns a StringMaybe it's better to go back "" (one String empty) instead null,
  • If your method returns a packed primitive type (Integer. Double. Long, etc.), it may be better to return instead of zero null, And if the return is zero, it is also a good idea to change the return type to the primitive type if possible.
  • If your method returns a arrayYou may want to a array rather zero in size than null,
  • If your method returns a CollectionMaybe it's better to go back Collections.emptyCollection(). Collections.emptyList() or Collections.emptySet() instead of null,
  • If your method returns a MapMaybe it's better to go back Collections.emptyMap() instead of null,
  • If your method returns a StreamMaybe it's better to go back Stream.empty() instead of null,
  • If your method returns a OptionalSo it's a bad idea to go back null because it goes directly against the idea of Optional, In this case it is better to go back Optional.empty() instead of null,
  • If your method returns something XYZ for which there is nothing that represents "empty", "not initialized", "not applicable", "not available" or "not found", you may change the return type to Optional be a good idea. Or you could use the design pattern. Zero object (which I will explain below).

In practice we can do something like this:

public class MeuBean {
    private String nome;
    private List pessoas;

    // Outros métodos...

    public String getNome() {
        return nome == null ? "" : nome;
    }

    public List getPessoas() {
        return pessoas == null ? Collections.emptyList() : pessoas;
    }
}

By the way, if we go back to the parameters, we can do something like the guards. Instead of just refusing nullWith exceptions, we can replace them with empty objects:

public void cadastrarNome(String nome) {
    String nomeParaCadastrar = nome == null ? "Sem nome" : nome;
    // ... Resto do método.
}

This approach has the advantage that, contrary to the previous mistake regarding the improper use of null They tend to disappear rather than just move. However, this approach is not always possible or appropriate.

Now let's take a closer look at the design pattern. Zero object, The idea is that you represent the terms "empty", "not available", "not found", etc. with an instance of an object instead of the null for this. Here is an example of this approach:

public class Pessoa {
    private String nome;
    private int idade;

    // ... Métodos.

    // Método que retorna um Null Object.
    public static Pessoa ninguem() {
        Pessoa naoTem = new Pessoa();
        naoTem.nome = "Ninguém";
        naoTem.idade = 0;
        return naoTem;
    }
}

public class Carro {
    private String modelo;
    private String cor;
    private int ano;
    private Pessoa proprietario;

    // ... Métodos.

    // Método que retorna um Null Object.
    public static Carro vazio() {
        Carro carroVazio = new Carro();
        carroVazio.modelo = "nenhum";
        carroVazio.cor = "nenhuma";
        carroVazio.ano = 0;
        carroVazio.proprietario = Pessoa.ninguem();
        return carroVazio;
    }
}

If you can work as interfaces, it is better to implement the standard. Zero object:

public interface Animal {
    public String fazerBarulho();
}

public class Cachorro implements Animal {
    @Override
    public String fazerBarulho() {
        return "Au au";
    }
}

public class Gato implements Animal {
    @Override
    public String fazerBarulho() {
        return "Miau";
    }
}

public class AnimalNenhum implements Animal {
    @Override
    public String fazerBarulho() {
        return "";
    }
}

Again, it is worth noting that you can take one of these approaches to avoid null if possible, However, one of them is not always possible and there are often situations in which one should really return null or accept that any field, parameter or local variable can be null Under normal circumstances you have to know how to deal with it. Know how to live with it nulls if they appear without causing a NullPointerException It is part of what the Java programmer should do.

Avoid all possibilities in the end NullPointerException Use the organization of your program's logic to prevent it from getting into situations where it appears. And in almost every situation in which one NullPointerException appears, it should be treated like a programming error (as is often the case): understand why it is occurring and correct the code so that it no longer occurs.


After all, it's worth recommending that SpotBugs, Successor to the famous FindBugs, It is an excellent and powerful Java code analysis tool that can detect a large number of logic errors, errors, dangerous situations and bad programming practices. And obviously all of this involves many situations that can lead to this NullPointerException,

And if you want to use that SpotBugs (or similar code verification tools) you may find a note @NotNull. @NonNull or @Nonnullalong with some notation @Null. @Nullable or @CheckForNull, Several people from many different projects have created multiple versions of these notes for similar purposes (which is bad, since it would be much better if there was one) @NotNull canonical and one @Nullable canonical). You can use these annotations in fields, variables, parameters, and methods to tell tools that can understand that a null in a certain place is expressly prohibited or allowed. The SpotBugs Can understand these notes even though he doesn't need them (but if they exist, he can do an even deeper analysis).

Another powerful tool is that Checker frameworkthat uses an annotative approach (including the @NonNull and the @Nullable) and works as a plug-in annotation processor directly in the compiler. With it, it is even possible to transform some places where a NullPointerException Compilation errors to avoid having to be tracked in tests and / or tests Debug,

java – Background service is not working properly on Samsung phones

I have created a service with a thread that gets the GPS position every 10 minutes and stores the longitude and latitude in the Sql Server bd. I did tests in the simulators with different APIs, also in LG, Huawei phones, but they work correctly but the same doesn't work well in samsung phones, that is, it saves on db or in 30 min, 1 h, 3 h never saves, the time varies without restriction, it should be noted that I did the tests in 3 different sansung models and they all behaved differently and none correctly. Also test setting in the battery restrictions so the service doesn't kill (this worked on Huawei phones), but it didn't work

Someone has an idea what could happen
Thanks anyway
My code is as follows

service

`  Conexion evento = new Conexion();
    Double latitud=0.0, longitud=0.0;
    String imei;
    String sfecha;


    @SuppressLint("MissingPermission")
    @Override
    public void onCreate() {

        imei=obtenerIMEI();
        LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Localizacion Local = new Localizacion();

        final boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!gpsEnabled) {`introducir el código aquí`
            Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(settingsIntent);
        }

        mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, (LocationListener) Local);
        mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, (LocationListener) Local);


    }
    public class Localizacion implements LocationListener {
        MainActivity mainActivity;
        public MainActivity getMainActivity() {
            return mainActivity;
        }
        public void setMainActivity(MainActivity mainActivity) {
            this.mainActivity = mainActivity;
        }
        @Override
        public void onLocationChanged(Location loc) {
            // Este metodo se ejecuta cada vez que el GPS recibe nuevas coordenadas
            // debido a la deteccion de un cambio de ubicacion
            latitud=  loc.getLatitude();
            longitud=loc.getLongitude();

        }
        @Override
        public void onProviderDisabled(String provider) {
            // Este metodo se ejecuta cuando el GPS es desactivado
            Intent i=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        }
        @Override
        public void onProviderEnabled(String provider) {
            // Este metodo se ejecuta cuando el GPS es activado

        }
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                case LocationProvider.AVAILABLE:
                    Log.d("debug", "LocationProvider.AVAILABLE");
                    break;
                case LocationProvider.OUT_OF_SERVICE:
                    Log.d("debug", "LocationProvider.OUT_OF_SERVICE");
                    break;
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
                    Log.d("debug", "LocationProvider.TEMPORARILY_UNAVAILABLE");
                    break;
            }
        }
    }
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        time time = new time();
        time.execute();
        return START_STICKY;
    }
    public void eje() {
        time time = new time();
        time.execute();
    }
    public void hilo() {
        try {
            Thread.sleep(600000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public class time extends AsyncTask {

        @Override
        protected Boolean doInBackground(Void... voids) {

            hilo();

            return true;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            ConnectivityManager con=(ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo=con.getActiveNetworkInfo();
            eje();
            //Toast.makeText(getApplicationContext(),"mensaje",Toast.LENGTH_SHORT).show();
            if (networkInfo!=null && networkInfo.isConnected()) {
                Registro_gps();

            }else {
                //  Toast.makeText(getApplicationContext(),"mensaje",Toast.LENGTH_SHORT).show();
            }
        }
    }



`
Parte del codigo donde ejecuta el servicio

     @Override
    protected void onCreate(Bundle savedInstanceState) {

        ConnectivityManager con = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = con.getActiveNetworkInfo();
         permisos();
            if (networkInfo != null && networkInfo.isConnected()) {
                imei = obtenerIMEI();
                startService(new Intent(MainActivity.this, SaveGPS.class));
            } else {
                mostrar_alerta().show();
            }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

Java – Reduce double numbers to two decimal places with DecimalFormat: Use of the API documented as @since 1.6+ error

I am trying to use this code to get the number 2.90:

double number = 2.90689;
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.FLOOR);  //error
System.out.println(df.format(number));

However, I get that Usage of API documented as @since 1.6+ error when trying to set the rounding mode. How do I solve this in a modern way? All the answers I've found use this seemingly outdated code.

scripting – comma break in mathematica like any programming language like java, php that we put behind the comma

My Mathematica compiler throws an error when I put an extra comma at the end of the while loop. Is there any other way to do this? Here is my code:

While[i <= N0,
i++;
p0 = g[p0];
Print[i, "t", N[p0, 3], "t", N[p0, 6], "t", N[Abs[a - p0], 6]];
If[Abs[a - p0] < tol, Print["The solution is: ", N[p0]]; Exit[]];
a = p0;
];

I'm making this code for a friend and she doesn't know the question. The first question is for loops and the doctor has asked them to do so during the process.
Here is an extract from the error location in the code:

Enter image description here

Java components for inserting, updating, deleting, validating and searching (vs service)

I have doubts about the implementation of these components (which are referred to as collaborators in our project): "Generators", "Erasers", "Finders", "Updators" etc. (our software architect wrote a document about them). He said that they will work with our actual services because they have too much responsibility at the moment.

generators: You generate an entity and then save it somewhere. Internally, you could call some methods from validators, mappers, repositories, etc.

deleter: You will delete entities. Internally, you could call some methods from validators, searchers, repositories, etc.

I think the orchestrator of all these calls is a service. Why should I transfer the service code to other "employees" who do exactly the same thing, but with a more complex model?

java – calculate compound interest

My job is to teach a trainee how to program. I told him to do the following task given by a book (I'm trying to translate it):

Write a compound interest calculation program. The user has to enter the amount of money, the years and the interest rate. The program should look like this:

Money in Euro: 100
Annual percentage rate: 6
Term in years: 4
Money after 1 years: 106.0
Money after 2 years: 112.36
Money after 3 years: 119.1016
Money after 4 years: 126.247696

Important note

He hasn't learned anything about OOP, exception handling, or the use of objects and methods. He is now learning to design simple algorithms. But he got a hint on how to use the scanner class to get user input.

I want to show him my own sample solution so he can learn. I want to ask you if my sample solution is ok to show to a beginner. Is it well written or have I ignored good practices?

// use "int variable = scanner.nextInt()" for getting int values
// use "double variable = scanner.nextDouble()" for getting double values

import java.util.Scanner;

public class Main {
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String args()) {
        // write your solution here:    
        double money;
        int years;
        double rate;

        System.out.print("Money in Euro: ");
        money = scanner.nextDouble();
        System.out.print("Annual percentage rate: ");
        rate = scanner.nextDouble();
        System.out.print("Term in years: ");
        years = scanner.nextInt();

        for (int i = 1; i <= years; i++) {
            money += money * (rate / 100);
            System.out.println("Money after " + i + ". years: " + money);
        }
    }
}

Java error in PrepareStatement

private void BtnConectarActionPerformed(java.awt.event.ActionEvent evt) {                                            

        try{ 
           Connection con =null;
           con = getConection();//llamo a la coneccion
           String sql="Select * from personas";
           PreparedStatement ps ; 
             ps=con.prepareStatement(sql);

        }catch(Exception e){
            System.out.println(e);
        }

-I am getting an error message that you cannot find the prepareStatement method and it is highlighted in red. Did it happen to someone and how did you solve it? I will be very grateful.

      ps=con.prepareStatement(sql);

This is the line that gives me the error

Java – how do I set errors on button like errors from edittext?

There is a button to select the time using the time selection dialog. I want to set an error if the time is not selected. I tried these codes below. The error occurs, but continues to appear after you select the time. I need help

if (TextUtils.isEmpty (btnDate.getText (). toString ())) {

        btnDate.setError("Bu alan boş olamaz");
        btnDate.requestFocus();
        return false;
    }

Java – fight for the AI ​​to repeat itself an infinite number of times

I follow this as a guideline to find simple AI for an enemy since I'm new to Java.

https://www.javacodegeeks.com/2014/08/game-ai-an-introduction-to-behaviour-trees.html

https://github.com/obviam/behavior-trees/tree/master/src/net/obviam/bt

I call this function:

AI goombaBrain = Routines.selector(Routines.repeatInfinite(Routines.wander(Board.board, InitObject.goomba)));

InitObject.goomba.setRoutine(goombaBrain);

However, once it has moved to a random location, it will not automatically reset. Any ideas? If you need more information, please let me know. (InitObject.goomba is the enemy)