2

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?

3
  • 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. Commented Jul 26, 2019 at 20:26
  • 1
    You should look into use cases for primitive int and Integer , since you should prefer int over Integer unless necessary, same goes for this scenario. Commented Jul 26, 2019 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. Commented Jul 26, 2019 at 20:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.