2.1) Creating objects of the wrapper classes

1)Class hierarchy of wrapper classes:

2) Creating objects of the wrapper classes:

You can create objects of all the wrapper classes in multiple ways:

  • Assignment—By assigning a primitive to a wrapper class variable

  • Constructor—By using wrapper class constructors

  • Static methods—By calling the static method of wrapper classes, like valueOf()

You can create objects of the rest of the wrapper classes (Short, Integer, Long, and Float) in a similar manner. All the wrapper classes define constructors to create an object using a corresponding primitive value or as a String.

Another interesting point to note is that neither of these classes defines a default no-argument constructor. Because wrapper classes are immutable, it doesn’t make sense to initialize the wrapper objects with the default primitive values if they can’t be modified later.

You can assign a primitive value directly to a reference variable of its wrapper class type—thanks to autoboxing. The reverse is unboxing, when an object of a primitive wrapper class is converted to its corresponding primitive value. I’ll discuss autoboxing and autounboxing in detail in the next section.

3) Retrieving primitive values from the wrapper classes:

All wrapper classes define methods of the format primitiveValue(), where primitive refers to the exact primitive data type name. Table shows a list of the classes and their methods to retrieve corresponding primitive values.

Example :

4) Parsing a string value to a primitive type:

To get a primitive data type value corresponding to a string value, you can use the static utility method parseDataType(), where DataType refers to the type of the return value. Each wrapper class (except Character) defines a method, to parse a String to the corresponding primitive value, listed as follows:

Example 1:

CTE

5) Difference between using method valueOf() and constructors of wrapper classes

Last updated

Was this helpful?