int and Integer - Java

Asked

Viewed 2,102 times

14

I’m developing a project in Java and he’s in error, I’ve found it but I don’t 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();
    }
}

He is generating Exception in thread "main" java.lang.NullPointerException, The reason is the private Integer gols; that’s like Integer, if I put int works normally.

  • Does anyone know why?
  • Aren’t the two the same thing? being int primitive and Integer object?

2 answers

15


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

The ideal is to use int same - as Integer 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

3

Integer is a class Wrapper which provides methods to the tipo primitivo int (if you want to know more proudly see this link Wrapper classes), then your property golsis not a tipo primitivo and yes an object nulo.

Browser other questions tagged

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