0
12kviews
What are the applications of wrapper classes? Explain.

Mumbai University > Information Technology > Sem 3 > Object Oriented Programming Methodology

Marks: 5 M

Year: Dec 2013, Dec 2014, May 2015

1 Answer
2
475views
  • 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.
  • Wrapper classes are used to convert primitive data types to object types by using the wrapper class contained in Java.lang package.
  • The table below shows the simple data types ad their corresponding wrapper class types.
Simple Type Wrapper Class
Boolean Boolean
Char Character
Double Double
Float Float
Int Integer
Long Long
  • There are mainly two applications of wrapper classes.

    1) To convert simple data types into objects, that is, to give object form to a data type; here constructors are used.

    2) To convert strings into data types (known as parsing operations), here methods of type parseXXX() are used.

  • For example,

    int k = 100;

    Integer it1 = new Integer(k);

    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.

    int m = it1.intValue();

    System.out.println(m*m); // prints 10000

  • intValue() is a method of Integer class that returns an int data type.
  • Conversion of Strings to Primitive data types can be carried out as follows:

    int i= Integer.parseInt(Str); //converts string to primitive integer

    long i= Long.parseLong(Str); //converts string to primitive long

Please log in to add an answer.