int and Integer - Java

13

I am developing a project in Java and it is in error, I have already found it but I do not understand it.

public class Time{

    private String nome;
    private ArrayList<Jogador> jogadores;
    private Integer gols;

    public void addGol(){
        this.gols = this.gols+1;
    }
}

public class App {

    public static void main (String args[]){

        Time time = new Time("A");

        time.addGol();
    }
}

It is generating Exception in thread "main" java.lang.NullPointerException , The reason is private Integer gols; that is as Integer , if I put int it works normally.

  • Does anyone know why?
  • Are not two the same? being int primitive and Integer object?
asked by anonymous 08.05.2015 / 01:16

2 answers

15

The default value for a int , if you do not specify any, is 0 . The default value for a reference, be it Integer or any other class, is null . Since you never specified the initial value of gols , when trying to increment it it can not - because the reference is null.

Ideally, you should use% w / o% itself - as int is immutable , it will create a new instance each time you do some operation with it. But if you want / need to use Integer , give it an initial value and the error will no longer occur:

public class Time{

    private String nome;
    private ArrayList<Jogador> jogadores;
    private Integer gols = 0; // ou new Integer(0), mas com o autoboxing tanto faz
    
08.05.2015 / 01:26
2

Integer is a Wrapper class that provides methods to tipo primitivo int (if you want to know more, see this link Wrapper classes ), so its gols property is not a tipo primitivo but a nulo object.     

08.05.2015 / 14:35