Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Why are wrapper classes needed?

On the very high level, I know that we need to "wrap" the primitive data types, such as int and char, by using their respective wrapper classes to use them within Java collections.I would like to understand how Java collections work at the low level by asking:"why do we need to wrap primitive data types as objects to be able to use them in collections?"I thank you in advance for your help.

like image 878
Midnight Blue Avatar asked Jan 25 '10 19:01

Midnight Blue


People also ask

What is the point of wrapper classes?

Wrapper classes are used to convert any data type into an object. The primitive data types are not objects; they do not belong to any class; they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language.


1 Answers

Because Java collections can only store Object References (so you need to box primitives to store them in collections).

Read this short article on Autoboxing for more info.

If you want the nitty gritty details, it pretty much boils down to the following:

Local Primitives are stored on the Stack. Collections store their values via a reference to an Object's memory location in the Heap. To get that reference for a local primitive, you have to box (take the value on the Stack and wrap it for storage on the Heap) the value.

like image 141
Justin Niessner Avatar answered Sep 19 '22 21:09

Justin Niessner