Jawari Joshak
Jawari Joshak

Reputation: 51

I don't understand wrapper class and autoboxing?

I am reading a book called "Java in Two Semesters" and I really don't understand wrapper class and autoboxing.

Can you please explain this to me with some code?

Also this is really bothering me:

Object [] anArray = new Object[20];
anArray[0] = new Integer (37);

What does Object refer to here, is object a class, and the code is creating an array for it?

I have got the book, I have a slight understanding, I just need someone to explain it to me briefly. If I read something online, I will just get confused.

Upvotes: 4

Views: 1376

Answers (3)

Patchikori Rajeswari
Patchikori Rajeswari

Reputation: 69

Wrapper Classes are used to convert primitive data types into objects and autoboxing means implicit conversion of primitive data type to equivalent wrapper class object, for example int will be converted to Integer object.

For more information read the below articles:

Explain Wrapper Classes in Java

Java 5/J2SE 5.0 new features : Autoboxing

Upvotes: 1

Low Flying Pelican
Low Flying Pelican

Reputation: 6054

Wrapper Classes

Wrapper classes are used to encapsulate primitive types so that operations can be defined against them. For example ToString() method is defined in wrapper class but it cannot be called on primitive type.

Autoboxing

Autoboxing allows to convert automatically between primitive types and wrapper types

With Autoboxing

int i;
Integer j;
i = 1;
j = 2;
i = j;
j = i;

Without Autoboxing

int i;
Integer j;
i = 1;
j = new Integer(2);
i = j.intValue();
j = new Integer(i)

About the second section of the question,

Object [] anArray = new Object[20];

The array defined is capable of Objects (in the specific case it's 20 objects), so it allows to hold any object in each position of the array,

anArray[0] = new Integer (37);

and Integer is a subclass of Object. So it allows to keep Integer in the array

Upvotes: 6

Michael Kingsmill
Michael Kingsmill

Reputation: 1863

Object is a class and anArray is being defined as an array of 20 objects. This allows you to stick things of different types in each index of the array, rather than forcing every index to be the exact same type. In the example, index 0 is set to an Integer, but index 1 could be set to a boolean value for example.

Upvotes: 0

Related Questions