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!

Linux for Beginners

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

Linux for Beginners doesn't make any assumptions about your background or knowledge of Linux. You need no prior knowledge to benefit from this book. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(101+ reviews)

More Linux & UNIX resources

Learn Enterprise Java Development for a Bright Career

Head First Java

Learn Enterprise Java Development for a Bright Career Try Java

Jump start your Java education with Head First Java! This book provides clean diagram examples, with text that is easy-to-understand in an almost too-casual language. Great for anyone new to Java or programming in general.

$ Check price
44.9544.95Amazon 4.5 logo(567+ reviews)

More Java resources

Ad