1

Say you have a method called 'setFloorNumber' that takes an integer that can't be null. Two different ways I figured you could do this:

public void setFloorNumber (@NonNull Integer floor){
   ...
}

or

public void setFloorNumber (int floor){
   ...
}

Best I can tell, they both accomplish the same thing which is requiring the integer parameter to not be null.

What are the pros and cons for these?

Is there a reason to want to choose one over the other, or are the differences negligible enough that it's purely just a stylistic choice?

DreamCloud
  • 113
  • 1
  • 9
  • 1
    Usually this is not something you need to handle. If someone incorrectly uses `setFloorNumber()` with a null Integer, just let a `NullPointerException` be thrown. Seems appropriate to me. – RaminS Jul 26 '19 at 20:26
  • 1
    You should look into [use cases for primitive int and Integer](https://stackoverflow.com/questions/6474576/java-primitive-types-int-vs-integer) , since you should prefer int over Integer unless necessary, same goes for this scenario. – Zohaib Amir Jul 26 '19 at 20:31
  • 1
    In general you should prefer `int` unless you have a really good reason to use `Integer` (such as storing numbers in a `List` or other container). One reason is to avoid unnecessary boxing and unboxing. – Code-Apprentice Jul 26 '19 at 20:32

1 Answers1

0

You are actually using two separate types.

If you use int than you cannot have a null value, it is a primitive type and it must be initialized to something, for instance int myNumber = 0; if you use an Integer, you are actually creating an Integer object. This is usually unnecessary and could be avoided.

Richard Dapice
  • 838
  • 5
  • 10