1
0

Wrapper Classes in Java

There are classes for all the primitive data types such as boolean, char, int, long, etc. as shown in the table. There are three purposes for having a class version of each basic type:

  • To provide an object wrapper for data values. A wrapper is useful because most of Java’s utility classes require the use of objects. Since variables of the primitive types are not objects in Java, it’s convenient to provide a simple way to “promote” them when needed.
  • To support some useful constants and methods associated with the type, like range boundaries and conversion to and from String class.
  • To give primitive types the same kind of introspection as non-primitive types. “Introspection” is a Java term for looking at the characteristics of a Java Object. It allows you to write component software, debuggers, class inspectors, and other systems programs in Java.
Primitive Data Types Corresponding Wrapper Class (in java.lang)
boolean Boolean
char Char
byte Byte
short Short
int Integer
long Long
float Float
double Double

Conversion of Primitive Numbers to Object Numbers using Constructor

Methods:

Conversion Let us suppose that age, fee, height, and phone are valid variables names denoting int, float, double and long data type. Then:

Integer val1 = new Integer(age);
Float val2 = new Float(fee);
Double val3 = new Double(height);
Long val4 = new Long(phone);

of Object Numbers to Primitive Numbers using typeValue() Methods:

In the above syntax, we have declared val1, val2, val3, and val4 as object numbers to Integer, Float, Double and Long types. We will use them to convert them into their corresponding type numbers i.e.

int num1 = val1.intValue();
float num2 = val2.floatValue();
double num3 = val3.doubleValue();
long num4 = val4.longValue();

Now, num1, num2, num3, and num4 are primitive numbers of their respective types.

Conversion of Object Numbers to Strings using string() Method:

In the above syntax, we have declared val1, val2, val3, and val4 as object numbers to Integer, Float, Double and Long type. We will use them to convert them into strings i.e.

First=Integer.toString(val1);
Second=Float.toString(val2);
Third=Double.toString(val3);
Fourth=Long.toString(val4);

Now, First, Second, Third, and Fourth act as String variables.

Conversion of String Objects to Numeric Objects using static method valueOf()

Method:

In the above syntax, we have declared First, Second, Third, and Fourth as Strings, and the below syntax will convert them into Integer, Float, Double and Long type using valueOf() method to num1, num2, num3, and num4 as follows:

num1 = Integer.valueOf(First);
num2 = Float.valueOf(Second);
num3 = Double.valueOf(Third);
num4 = Long.valueOf(Fourth);

Leave a Reply