What is Nullpointerexception and what are its main causes?

Asked

Viewed 56,799 times

71

  • What are the exceptions NullPointerException?
  • What are its main causes?
  • What methods/practices can be used to prevent?
  • One of the main causes is when Voce attempts to access a position that does not exist in the array/array. Type the vector have 5 positions and then try to access the sixth position.. That is, it does not exist!

  • http://www.devmedia.com.br/java-lang-nullpointerexception-dica/28677

  • 6

    That you spoke of position outside the interval is IndexOutOfBoundsException. Already access a position within the range but not initialized array would give NullPointerException.

6 answers

74


The NullPointerException is launched when attempting to use the null as if it were an object. That is, when you try to manipulate the properties, fields, attributes or methods of an object, but without having that object.

In many other programming languages there is also the same concept. For example, in C# there is the NullReferenceException. In Javascript, try to manipulate a null incorrectly produces a TypeError. Similarly, to manipulate None incorrectly in Python, produces a AttributeError.

The rest of this answer applies to Java, as referenced in the question. But in other programming languages, what happens is usually very similar to what is detailed below.


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

  1. Trying to access a field of an instance whose reference is null.

    Pessoa p = null;
    String nome = p.nome; // <-- NullPointerException aqui.
    
  2. Trying to access a method from an instance whose reference is null.

    Pessoa p = null;
    String nome = p.getNome(); // <-- NullPointerException aqui.
    
  3. Try to use autounboxing of null. This particular one tends to be a practical joke for beginners in Java.

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

    Another example:

    Integer x = null;
    int z = x + 5; // <-- NullPointerException aqui.
    
  4. Launch the NullPointerException directly (obvious).

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

    Exception x = null;
    throw x; // <-- NullPointerException aqui.
    
  6. Trying to access the size of a variable array that has the value null.

    String[] x = null;
    int tamanho = x.length; // <-- NullPointerException aqui.
    
  7. Trying to access an element of a variable array that has the value null.

    String[] x = null;
    String y = x[5]; // <-- NullPointerException aqui.
    
  8. Iterate null using 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. Attempt to obtain a method reference from null:

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

The following situations NAY cause NullPointerException, at least not directly:

  1. Assign null to the object type variables.

    String x = null;
    
  2. Assign null to variables of primitive types. This does not compile, so it will not give NullPointerException :)

    int x = null; // Erro de compilação!
    
  3. Pass by null as a method parameter 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 return of some method.

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

    String[] array = new String[] {"a", "b", "c"};
    array[1] = null;
    String valor = array[1]; // Ok. Recebe null.
    
  6. Pass by 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 a array or Collection with elements null.

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

    However, although this is valid and even useful at times, it is important to bear in mind that this situation is still very inviting to eventual NullPointerExceptions, since it is not normally expected that the loop variable can 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 from a reference null. This is a joke of the Java language, because in this case the only thing that matters is the type of the variable, and not the value.

    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, as it confuses code by using a variable unnecessarily. Don’t do this.

  9. Trying to use an uninitialized or potentially uninitialized local variable. This gives build error, so it does not give 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 worth noting that this rule only applies to local variables within methods and constructors. It NAY applies to object fields and static variables.

  10. Remember that the reference this will never be null. Therefore a NullPointerException will never be caused due to the attempt to manipulate fields and invoke methods in the object this.

  11. A constructor never returns null. Therefore, whenever the result of a constructor’s call is assigned to a variable, assuredly what will be assigned will be something that is not null. Therefore, taking as an example the code below, it is impossible that the variable p receive null, regardless of what is occurring inside the constructor.

    Pessoa p = new Pessoa();
    
  12. The operator instanceof always results in false when tested with null, and never casts NullPointerException. So if it turns out to be true, the tested value is guaranteed not to be null.

    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. Casts never launch NullPointerExceptions (but may cast ClassCastExceptions). In particular, the cast conducted 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 people think they can access one array in an invalid index causes a NullPointerException. That is not true. The exception in this case will be ArrayIndexOutOfBoundsException. Also, try 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 concatenate null to a String.

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

Almost every case where a NullPointerException occurs if it is due to some programming error (and because of this, it almost never makes sense to try to treat it). Therefore, if you get a NullPointerException, probably you (or someone else) did something wrong in the code. For this reason, to protect yourself against the NullPointerException, the main thing to do is to examine the logic of your program to make sure that you will never fall into a case where a NullPointerException can be released, as shown in the above situations at the beginning of this response (and with the above counter-examples as well). Its main weapon against this kind of mistake is the if:

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

It is also valid to place guards in methods (and builders) to protect against null references from "outside", using the if. This will not make the programming error involving references null disappear, but will make them manifest closer to their origin, having then an easier identification and therefore being easier to trace and correct. In addition, this makes it easier to ensure that your method is error-free, as this eliminates a whole category of possible programming errors that it could have and as a gift you ensure that it will not cause any strange side effects by running only half before being aborted by NullPointerException. The idea is that if the null is being used improperly (which is a programming error), so the programming error will not be the responsibility of your method, but of who called it improperly. Here’s 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 else, you can use a different 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 also not limited to parameter validation only:

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 by using the method Objects.requireNonNull(). This method launches a NullPointerException is 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<String> 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).

Just like protecting yourself from nulls coming from outside with the guards shown above, it is also important not to propagate values nulls if you can avoid this. Because of this, it is good to also avoid returning nulls in the methods when it is to return something that represents "empty", "not initialized", "does not apply", "does not exist" or "not found". In these cases, here’s what you could do:

  • Should your method return a String, maybe it’s best to return "" (one String empty) instead of null.
  • If your method returns a packaged type of primitive (Integer, Double, Long, etc.), it might be better to return zero instead of null. And if it is the case to return zero, change the type of return to the primitive type, if possible, it would also be a good idea.
  • Should your method return a array, maybe it’s best to return a array zero size instead of null.
  • Should your method return a Collection, maybe it’s best to return Collections.emptyCollection(), Collections.emptyList() or Collections.emptySet() instead of null.
  • Should your method return a Map, maybe it’s best to return Collections.emptyMap() instead of null.
  • Should your method return a Stream, maybe it’s best to return Stream.empty() instead of null.
  • Should your method return a Optional, then it’s a bad idea to return null because it goes directly against the idea of Optional. In this case it would be better to return Optional.empty() instead of null.
  • Should your method return anything XYZ for which there is nothing that represents the "void", "not initialized", "does not apply", "does not exist" or "not found", perhaps changing the type of return to Optional<XYZ> be a good idea. Or else you could use the project pattern Null Object (that I will explain a little below).

In practice, we can do something like this:

public class MeuBean {
    private String nome;
    private List<Pessoa> pessoas;

    // Outros métodos...

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

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

And by the way, back to the parameters, we can do something similar to the guards. Instead of just rejecting the 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, unlike the previous one, errors concerning the inappropriate use of null tend to actually disappear rather than just move. However, this approach is not always possible or appropriate.

And now, let’s take a closer look at the design pattern Null Object. The idea is that you represent the concepts of "empty", "does not exist", "not found", etc. with an instance of an object, rather than using the null to do so. 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 Null 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 adopt one of these approaches to avoid the null if possible. However, not always one of them is possible and it is common to appear some situations where one really should return null or accept that some field, parameter or local variable may be null under normal circumstances, and you have to know how to live with it. Know how to live with the nullwhen they appear without causing a NullPointerException is part of what the Java programmer should do.

In the end, all ways to avoid the NullPointerException is to organize the logic of your program so as to avoid falling into any of the situations where it may appear. And in almost every situation where a NullPointerException appears, it should be treated as a programming error (as indeed it almost always is): understand why it occurs and fix the code to no longer occur.


Finally, it is worth recommending Spotbugs, successor of the famous Findbugs. It is an excellent and powerful Java code analysis tool, capable of detecting a lot of logic errors, bugs, dangerous situations and bad programming practices. And all of this obviously includes many situations that can result in NullPointerException.

And if you’re gonna use the Spotbugs (or some other code checking tools with similar features), you may find an annotation @NotNull, @NonNull or @Nonnull, along with some note @Null, @Nullable or @CheckForNull. Several people from several different projects have created several versions of these annotations with similar purposes (which is bad, because it would be much better if there were only one @NotNull canonical and a single @Nullable canonical). You can use these annotations in fields, variables, parameters and methods to tell the tools able to understand them that a null in a given place is explicitly prohibited or permitted. The Spotbugs is able to understand such notes, although he does not need them (but if they are present, he can make an even deeper analysis).

Another powerful tool is the Checker Framework, using an annotation-based approach (including @NonNull and the @Nullable) and acts as a plug-in annotation processor directly on the compiler. With it, it is even possible to transform some places where a NullPointerException compile errors, avoiding the headache of having to track them in tests and/or debugging.

  • 2

    Wouldn’t it be better just to get around the problem of NullPointerException (i.e. calling for data re-entry), rather than making another exception?

  • 3

    @Patrick, sometimes yes, you could put that inside the while and only let it go when the die is different from null. But in practice, this specific situation of asking for data reentry is rare. The big deal here is: 1. To know and understand why the null appeared in each particular case. 2. Knowing if it is valid it actually appears and correcting the code if it is not. 3. If it is in fact valid, correct the code to treat it properly. In the end everything ends up falling into designing the logic of the program so as to ensure that all nullare handled safely.

15

The exception Nullpointerexception is launched when trying to use an object that has not yet been instantiated.

Based on this class:

public class Endereco{
    public String rua;
    public String localidade;

    public Endereco(String rua, String localidade){
        this.rua = rua;
        this.localidade = localidade;
    }
    public String getMoradaCompleta(){
        return rua + "," + localidade;
    }
}

The most common situations are the following:

1 - Calling an instance method of an uninstalled object.

public printMoradaCompleta(Endereco endereco){
    String morada = endereco.getMoradaCompleta();
    System.out.println(morada);
}

2 - Access or modify a field of an instantiated object.

public printRua(Endereco endereco){
    String rua = endereco.rua;  
    System.out.println(rua);
}

3 - Access or modify an element of an array that has not been initialized.

public int getSecondElementFromArray(int[] array){

    return array[1];
}

In situations 1 and 2 the methods will fail if the endereco past is null.
In situation 3 the method will fail if array be it null or no value has been assigned to the second element of the array.

The way to prevent these situations is to check whether the parameter passed to the method is not null and if it is to launch a IllegalArgumentException:

public printMoradaCompleta(Endereco endereco){
    if(endereco == null){
        throw new IllegalArgumentException("O endereço não pode ser nulo");
    }
    String morada = endereco.getMoradaCompleta();
    System.out.println(morada);
}

Here can be found a more complete article on the subject:

  • 2

    I just wanted to tell you that variable and method names should start with lower case, following the conventions of Java names (even the syntax coloring here is affected by this). Plus, there’s one missing + in his method MoradaCompleta in class Endereco so that it can compile, but below you use getMoradaCompleta instead of MoradaCompleta.

  • 1

    Finally, your answer is simply to check that the parameters of a method are null and to launch a IllegalArgumentException if it is. But there is much more to be done to avoid the NullPointerException. Here you’d just be changing the NullPointerException by a IllegalArgumentException in a method parameter, which probably does not solve the main problem of most beginners using Java, which is not sure when a reference is null or not.

  • 1

    I appreciate your comments. All the code was written directly in the reply box having no help to syntax corrector. In addition, the code snippets are exemplifying and in this case it is not relevant to compile for the reasons you pointed out. Of course, we must always be careful to prevent such errors from occurring. The answer could, in fact, be more complete but would become very extensive, hence the link to the article. I look forward to post an answer that will certainly complement/exceed my.

  • 2

    @ramaral not to take the bad. But, his code is outside the standards of java as already mentioned and really, it does not compile. You couldn’t edit and fix it ?

  • 2

    @wryel Edited.

  • I just came across a situation where giving a get in a Boolean returned me too.

Show 1 more comment

10

What is Nullpointerexception?

Nullpointerexception is an exception thrown when trying to access members of a non-existent object.

That is, the code assumes that a given variable references an instance of an object and attempts to access members of that instance; then, when there is no instance of fact (the variable points to null instead of referencing an object), a Nullpointerexception will be launched.

Behold:

Pessoa pessoa = new Pessoa();

In the above code, the variable person references an object - it references an instance of Person.

Pessoa pessoa = null;

And in the above code the variable person does not reference any object. We can say that it "points to null" but the most usual is to say that "the variable is null".

If you pass to a method any this variable is null and this method try to access a member of the object that it presumes to exist, will be launched a Nullpointerexception:

public void processaPessoa(Pessoa pessoa) {
    int idade = pessoa.getIdade(); //se pessoa é null, aqui será lançada uma NullPointerException.
    ... 
}

What are the main causes of Nullpointerexception?

This exception occurs basically for two reasons:

a) Programming error.

b) Library or framework usage error.

One Nullpointerexception released by your code is a programming error you made. And if it is released by the code of a third-party library or framework, it is not necessarily their programming error - it is more likely that you are using the library the wrong way (you stopped configuring something or configured it the wrong way, for example).

What methods or practices can be used to prevent Nullpointerexception?

To prevent this exception you must avoid making programming mistakes.

'Cause it’s a programming error if your code launches a Nullpointerexception? Because if that happens then you wrote code to be used one way and you’re using it another way.

Consider this method:

public void processaPessoa(Pessoa pessoa) {
    // ... não importa o código que tem aqui.
}

The above method should never launch a Nullpointerexception for person was null because you should never pass a variable null for him!

The method signature (its name and the parameter it expects) makes it very obvious that it needs a type object Person to work. Passing a null variable to this method is a programming error.

Treat at the beginning of the method if the variable is null may help diagnose programming error but I consider it a bad practice because the code will get dirty with validations that are not expressive for the business.

These are expressive validations for the business:

public void processaPessoa(Pessoa pessoa) {
    if (pessoa.getIdade() < 18) {
      throw new BusinessException("A pessoa precisa ser maior de idade para poder ser processada");
    }
    if (pessoa.getNotificacao() == null) {
      throw new BusinessException("A pessoa precisa ter sido notificada antes de ser processada.");
    }
    ... 
}

This other one is a bad validation because it is soiling the code with instructions that has nothing to do with the business:

public void processaPessoa(Pessoa pessoa) {
    if (pessoa == null) {
        throw new InvalidArgumentExcetion("O parâmetro 'pessoa' não pode ser null.");
    }
    ... 
}

This type of validation is sometimes advocated for facilitating the diagnosis of errors, but it is not much more difficult to understand which person is null simply letting one burst Nullpointerexception further down. So I choose to keep the code cleaner and more expressive and do not do this kind of validation.

Validations like this should be done at the highest levels of the application, in the data entry. For example:

// usuário entrou com o CPF da pessoa que ele quer processar

Pessoa pessoa = pessoas.find(cpf);
if (pessoa == null) {
    throw EntityNotFoundException("Não foi localizada nenhuma pessoa com o CPF " + cpf);
}
processaPessoa(pessoa);

A common error when trying to prevent Nullpointerexception

For ingenuity or for some non-virtuous feature, there are programmers who get rid of Nullpointerexception so:

public void processaPessoa(Pessoa pessoa) {
    if (pessoa != null) {
        // código para processar a pessoa.
    } // fim do método
}

The above method will never fail per person being null, but the system will probably fail and will be in the worst possible way: silently.

Everyone will be thinking that someone was sued but this did not occur and no warning was given.

Then the Nullpointerexception was avoided at the cost of the system having its integrity corrupted.

Completion

Nullpointerexception is an exception thrown when trying to access members of a non-existent object.

The way to avoid it nay is validating at the beginning of the method if the arguments are null (at least not most of the time).

The way to avoid it is by validating data entry at the highest application levels (user inputs, values in configuration files, service facade for external consumption, etc.) and writing expressive code so your consumers know how to consume it.

In addition, it is sometimes valid in the domain that an object does not exist (see above for the example of the person who could not be processed because they had not been notified). In these cases, the existence of the object must be validated before it is used so that we have an expressive error for the business instead of having a Nullpointerexception.

Finally, libraries and frameworks launch Nullpointerexception when they are used incorrectly.

When a Nullpointerexception is released by libraries or frameworks (by the application server, for example) we were very angry because we wanted them to have validated the parameters and launched a more expressive error. But, as I said, it’s usually harder to figure out why a variable got null up there than to simply identify that a certain parameter is null.

10

This exception is thrown whenever trying to access an object that has not yet been initialized.

What can cast the exception:

  • Accessing null object methods.
  • Access or modify null object fields.
  • Catch the length of a null
  • Access or modify the slots of a null
  • Cast an exception as if it were 'flitable'

In Java, it is always necessary to do two things with any object:

  • Declare the object;
  • Initialize object (set a value other than null) - this avoids the NullPointerException

Former commons:

first case:

ArrayList<String> texto = null; //definido como null
texto.add("texto");

2nd case: // think that the person class has already been created with the name attribute and the get/set

Pessoa p;
System.out.Println(p.getNome());

third case:

ArrayList<String> texto = null;
int i = texto.length;

fourth case:

Pessoa p = new Pessoa("maria");
Pessoa pessoas[] = null; 
pessoas[0] = p;

In all cases, what was missing?

INITIALIZE THE OBJECT (WITHOUT null)!!

Source: Javadoc

  • 1

    I think the phrases "Declare the object" and "Initialize the object" may be confused or even wrong, in the context you put, because what is declared is the reference variable, that when properly initialized is referencing an object in memory. Objects in turn are not declared, are instantiated and may or may not be referenced by variables.

  • Actually, class and variable instances are objects, right? If I am referring to both (classes and variables), how can I choose between declaring and instantiating?

  • I may be being detailed, but object and variable are different things. For example the p in Pessoa p; is a variable, not an object. Just as it is possible to create an object without declaring a variable to reference it, so: new Pessoa().getNome();.

  • This being detailed hehe but became difficult to understand what I meant? If it was mute there, but I don’t think I should be crucified for it :P Until the/

  • Surely it should not be sacrificed, rs.. otherwise it would have taken several negatives. I am only making one point clear of your potentially inaccurate answer. The answer is yours, change if you feel you should ;-)

4

This error always occurs when I try to capture information that had no value assigned.

Example:

You have in your BEAN a class Client.

In your main class you instance Client

Cliente cliente = new Cliente();

The error occurs when for example you will print the client code.

System.out.println(cliente.getCodigo);

(Note that at no time do we assign value to the client code, then the compiler will display the error NullPointerException, you’re trying to print something empty).

assign the value to cliente.setCodigo(1); then print normally will work.

CORRECTION:
This exception will not be displayed on println (as it can handle null information).
The same problem would be to assign the value to a jtextfiel, example: seuTextField.setText(client.getCodigo());
//The error will happen because we have nothing assigned to the client code.

  • I voted against for the following reasons:: Cliente cliente = new Cliente(); System.out.println(cliente.getCodigo); would print null. Can’t NullPointerException. The System.out.println has no problem receiving null, then it would be no problem to try to print empty. Say the compiler launches the NullPointerException it is absurd, who would launch it would be the JVM. Moreover you forgot the parentheses after the getCodigo.

  • Truth @Victor-stafusa, the problem occurs not when we print in println, but when we will for example assign the information to a jTextFiel. (Example: seuTextField.setText(client.getCod()); ) #excuses

0

In Java, every variable or constant needs an instance to be used, assuming we have a User class, and we pass the name in the constructor:

Usuario usuarioVariavel = new Usuario("João");
usuarioVariavel = new Usuario("Felipe");

In the example above, the variable "userVariable" was with the instance of name "John", then was assigned a new instance of name "Philip", forgetting "John"

Nullpointerexception is the access of a method or attribute of a variable that has no instance

For example:

Usuario usuario = null;
int idade = usuario.getIdade(); //Gera NullPointerException

The best way to prevent this is to check whether the object has an instance (other than null), for example:

if(usuario!=null){
     int idade = usuario.getIdade();
     //...
}

Another way, but of lower performance (since when an exception is launched Java has to seek information about it) is the exception treatment:

try{
    int idade = usuario.getIdade();
}catch(NullPointerException npe){
    //Usuário não possui instância
}

Often we can avoid Nullpointerexception when the access of a method or attribute need not be necessarily from a specific instance, but rather, the class itself holds a certain value, where everyone calling such a class can use the method or attribute, for this we define the method and/or attribute as "Static"

public class Usuario{
   private static int quantidadeUsuarios = 0;
   public static int getQuantidadeUsuarios(){
        return quantidadeUsuarios;
   } 
}

And call:

int quantidade = Usuario.getQuantidadeUsuarios();  
//Não gera NullPointerException, porque o método não pertence à uma instância específica

Browser other questions tagged

You are not signed in. Login or sign up in order to post.