Page 150 - Computer science 868 Class 12
P. 150
5.4.1 Syntax of using a Wrapper Class
Since a wrapper class helps convert primitive data types into objects and vice-versa, we must learn both syntaxes. They
are given as follows:
• Converting Primitive data type into String
String Variable = <Wrapper class>.toString(<datatype>);
For example: String number_int = Integer.toString(54);
Output: “54”
• Converting String into Primitive data type
There are two ways to convert a String into a primitive data type. They are:
<datatype> Variable = <Wrapper class>.parse<Wrapper class>(String);
For example: int var = Integer.parseInt("54");
Output: 54
<datatype> Variable = <Wrapper class>.valueOf(String);
For example: String str = Integer.valueOf(54);
Output: “54”
5.4.2 Autoboxing
Autoboxing is a method of converting a primitive data type into an object of its corresponding wrapper class. For
example, an int data type variable is converted into its object by wrapping the value with the wrapper class “Integer”.
Similarly, a double variable is wrapped by the Double wrapper class and so on. Autoboxing is an automatic conversion
done by the Java compiler.
The concept of autoboxing is required when a primitive value is:
• passed as a parameter to a function that expects an object of the equivalent wrapper class.
• initialised to a variable of the corresponding wrapper class.
Syntax:
<Wrapper class> <object name> = new <Wrapper class>(Primitive Value)
For example, converting double into Double class:
double d_datatype = 267.5689;
Double d = new Double(d_datatype);
5.4.3 Unboxing
Unboxing is a method of converting an object of a wrapper class into its corresponding primitive data type value. For
example, an object of the Integer class is converted into an int variable, and so on.
Unboxing is used when an object of a wrapper class is:
• passed as a parameter to a function that will work on the value of the equivalent primitive type.
• initialised to a variable of the corresponding primitive type.
Syntax:
<Primitive Data Type> variable = <Wrapper Object>
For example, converting Double class into double:
double d_object = new Double(267.5689);
double d_datatype = d_object;
Program related to AutoBoxing and UnBoxing:
class final_keyword
{
148148 Touchpad Computer Science-XII

