When I should go for wrapper class over primitive types? Or On what circumstance I should choose between wrapper / Primitive types?
Java – When to use wrapper class and primitive type
javaprimitive-typeswrapper
Related Topic
- Java inner class and static nested class
- Java – a serialVersionUID and why should I use it
- Java – How to read / convert an InputStream into a String in Java
- Java – When to use LinkedList over ArrayList in Java
- Java – Difference between StringBuilder and StringBuffer
- Java – a JavaBean exactly
- Java – Why is processing a sorted array faster than processing an unsorted array
- Java – Proper use cases for Android UserManager.isUserAGoat()
Best Answer
Others have mentioned that certain constructs such as
Collections
require objects and that objects have more overhead than their primitive counterparts (memory & boxing).Another consideration is:
It can be handy to initialize Objects to
null
or sendnull
parameters into a method/constructor to indicate state or function. This can't be done with primitives.Many programmers initialize numbers to 0 (default) or -1 to signify this, but depending on the scenario, this may be incorrect or misleading.
This will also set the scene for a
NullPointerException
when something is being used incorrectly, which is much more programmer-friendly than some arbitrary bug down the line.