Why are there wrapper classes in Java? [duplicate]
I know what a wrapper class is, they wrap primitive types (e.g. int, double, etc) to objects of their respective class.
But, why do we need Wrapper classes in the first place? Why not simply go with primitive types where we have them?
Several possible reasons:
- So that a null value is possible
- To include in a Collection
- To treat generically / polymorphically as an Object along with other Objects
Am example of when wrappers are used would be in Collections, you can have an ArrayList<Integer>
, but not an ArrayList<int>
same with HashMap
s etc. To get type safety we use generics and generics need objects not primitives.
Java is an object oriented programming language. I think you could also ask - why do we have primitives and why is everything not just an object?
Java designers kept the two separate to keep things simple. You use the wrappers when you need types that fit in the object oriented world - like polymorphism, collections etc. You use the primitives when you need efficiency.