03. Autoboxing

One of the restrictions with Java Generics is that they must be instantiated with a reference type. This means you cannot use a primitive type such as int, char or double. Instead, we must use its corresponding non-primitive type (eg. Integer, Character, Double).

Luckily, Java automatically converts a primitive type to its corresponding reference type; this is known as autoboxing..

So for example, when we place an item into our container of primitive type, such as the number 50, converts it an equivalent refernece type.

Thus we have int morphing into Integer.

intContainer.add(50);
// is actually doing this...
intContainer.add(new Integer(50));

In contrast, auto-unboxing occurs when retrieving that same item from our collection.

// from Integer to int
int i = intContainer.getData(); 

Take your Linux skills to the next level!

How Linux Works

Take your Linux skills to the next level! Try Linux & UNIX

In this completely revised second edition of the perennial best seller How Linux Works, author Brian Ward makes the concepts behind Linux internals accessible to anyone curious about the inner workings of the operating system. Inside, you'll find the kind of knowledge that normally comes from years of experience doing things the hard way.

$ Check price
39.9539.95Amazon 5 logo(114+ reviews)

More Linux & UNIX resources

Learn Enterprise Java Development for a Bright Career

Effective Java

Learn Enterprise Java Development for a Bright Career Try Java

Are you looking for a deeper understanding of the Java so that you can write code that is clearer, more correct, more robust, and more reusable? Look no further! Effective Java brings together seventy-eight indispensable programmer's rules of thumb: working, best-practice solutions for the programming challenges you encounter every day.

$ Check price
54.9954.99Amazon 4.5 logo(219+ reviews)

More Java resources

Ad