❮ Previous Next ❯

Java Wrapper classes

As the name says, a wrapper class wraps (encloses) around a data type and gives it an object appearance. Wherever, the data type is required as an object, this object can be used. Wrapper classes include methods to unwrap the object and give back the data type. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.

Observe the following conversion.

The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.
The following code can be used to unwrap (getting back int from Integer object) the object it1.

intValue() is a method of Integer class that returns an int data type

List of Wrapper classes

In the above code, Integer class is known as a wrapper class (because it wraps around int data type to give it an impression of object). To wrap (or to convert) each primitive data type, there comes a wrapper class. Eight wrapper classes exist in java.lang package that represent 8 data types. Following list gives.

Primitive data type Wrapper class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
Boolean Boolean

All the 8 wrapper classes are placed in java.lang package so that they are implicitly imported and made available to the programmer. As you can observe in the above hierarchy, the super class of all numeric wrapper classes is Number and the super class for Character and Boolean is Object. All the wrapper classes are defined as final and thus designers prevented them from inheritance.

There are mainly two uses with wrapper classes.

Let's see the following program which expresses the style of converting data type into an object and at the same time retrieving the data type from the object.

Example

class Demo2
{
public static void main(String args[])
{
byte grade=2;
int marks=50;
float price=8.6f;
double rate=50.5;
Byte g1=new Byte(grade);
Integer m1=new Integer(marks);
Float f1=new Float(price);
Double r1=new Double(rate);
System.out.println("Byte object g1:"+g1);
System.out.println("Integer object m1:"+m1);
System.out.println("Float object f1:"+f1);
System.out.println("Double object r1:"+r1);
byte bv=g1.byteValue();
int iv=m1.intValue();
float fr=f1.floatValue();
double dv=r1.doubleValue();
System.out.println(bv);
System.out.println(iv);
System.out.println(fr);
System.out.println(dv);
}
}
❮ Previous Next ❯



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved