Skip to content

(Java) Choosing the right variable type: int vs Integer

Kristina edited this page Jan 4, 2018 · 1 revision

You may have noticed that you can assign numbers to both int and Integer. Some developers just randomly select one of the variable types without thinking about the differences between them and normally that works. However sometimes not selecting the right one will cause the code to crash.

int is a primitive data type variable that accepts a number and has a default value of 0.

Integer is a wrapper class for int which adds several methods that you can read about here and has a default value of null.

Unless you need any of the extra methods that the Integer class has and don't need to check if the variable is set then int is what you should use.

Integer is a good choice if you need to see if the variable was set (it will be null if it was never set to a value) or if you need to use the methods that a Integer variable type comes with.

When dealing with Spring Data JPA you should assign the int to any numeric entity fields that are not nullable in the database and use Integer for numeric fields that are nullable.

Clone this wiki locally