Wrapper classes


Introduction

Java is an object-oriented language and can view everything as an object. A simple file can be treated as an object (with java.io.File), an address of a system can be seen as an object (with java.util.URL), an image can be treated as an object (with java.awt.Image) and a simple data type can be converted into an object (with wrapper classes). This tutorial discusses wrapper classes. Wrapper classes are used to convert any data type into an object.

The primitive data types are not objects; they do not belong to any class; they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language. For example, upto JDK1.4, the data structures accept only objects to store. A data type is to be converted into an object and then added to a Stack or Vector etc. For this conversion, the designers introduced wrapper classes.

What are 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.

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.

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


Following is the hierarchy of the above classes.



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.

Importance of Wrapper classes

There are mainly two uses with 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.

The following program expresses the style of converting data type into an object and at the same time retrieving the data type from the object.

public class WrappingUnwrapping
{
  public static void main(String args[])
  {				                  //  data types
    byte grade = 2;
    int marks = 50;
    float price = 8.6f;       		          // observe a suffix of f for float
    double rate = 50.5;
 		                                  // data types to objects		
    Byte g1 = new Byte(grade);                    // wrapping  
    Integer m1 = new Integer(marks);
    Float f1 = new Float(price);
    Double r1 = new Double(rate);
                                                                    // let us print the values from objects	
    System.out.println("Values of Wrapper objects (printing as objects)");
    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);
	        // objects to data types (retrieving data types from objects)
    byte bv = g1.byteValue();                 // unwrapping 
    int iv = m1.intValue();
    float fv = f1.floatValue();
    double dv = r1.doubleValue();
                                                                    // let us print the values from data types	
    System.out.println("Unwrapped values (printing as data types)");
    System.out.println("byte value, bv: " + bv);
    System.out.println("int value, iv: " + iv);
    System.out.println("float value, fv: " + fv);
    System.out.println("double value, dv: " + dv);
  }
}


As you can observe from the screenshot, constructors of wrapper classes are used to convert data types into objects and the methods of the form XXXValue() are used to retrieve back the data type from the object.

Scroll down and click over Page 2 to go for next page

87 thoughts on “Wrapper classes”

  1. int a=10;

    Integer in=new Integer(10);

    here internally toString method is going to be orveride withf the WrapperClass of toStringMethod so it returns the string but how we can tell that it returns the number as the 10 value

    ??Myquestion is it returns toString Method ok but it has to return the String value ok but it can add as a object but it is adding as a String value how can it is added

  2. Hi,
    I have a doubt in Number class, ie in the following example what is the difference in the three print statements ? ( why three are giving same output as 10 ?)
    —————————————————————————————
    let,

    Integer In =10;
    System.out.println(In);
    System.out.println(In.intValue());
    System.out.println(In.hashCode());
    ————————————————————————————-
    please help me out. !

    1. Due to autoboxing feature In calls internally intValue() and prints 10 in the first println statement. In the second one, you are calling yourself intValue(). hashCode is most used with strings and collection objects to compare which is very fast. The third println statement also prints 10 as hashCode() method of Object class is overridden in Integer class with its own implementation of printing the number.

  3. Integer i = new Integer(10);
    Here in the above the Integer constructor is created and it’s address is given as reference for i;
    when i am trying to print the i value it is printing as 10;
    But if i try with any other class
    for Ex:- Count count1 = new Count();
    System.out.println(count1);
    System.out.println(count1.hashCode());

    the values are different for this case. But they are not varying above method. May i know why?
    Is there any chance that parameter passed in the integer class itself acts as an address and hash code.

    Please give me explanation what was happening……..

    1. java accepts everthing by deafault in string format..wrapper class is use to convert them into primitive or required data type…

  4. Rahul Chudasama

    We can do our code with primitive data types , what is the practical use of that???
    At what scenario we can use this?

  5. wap to add two numbers irrespective to the data typeby getting from command line arguments.
    can you solve it plzzzz…..

  6. thanks a lot…
    wasnt able to undeestand dis topic frm other sources
    really simple language and well defined with examples

  7. This line: add(new JScrollPane(canvas), BorderLayout.CENTER); is giving me error- incompatible types: PaintCanvas cannot be converted to Component.
    Please help

  8. Hi,
    I am getting the following errors
    D:\java\jdk\bin\Programs\Wrapper classes>javac Conversion.java
    Conversion.java:28: cannot find symbol
    symbol : method bytevalue()
    location: class java.lang.Byte
    byte bv = g1.bytevalue();
    ^
    Conversion.java:29: cannot find symbol
    symbol : method intvalue()
    location: class java.lang.Integer
    int iv = m1.intvalue();
    ^
    Conversion.java:30: cannot find symbol
    symbol : method floatvalue()
    location: class java.lang.Float
    float fv = f1.floatvalue();
    ^
    Conversion.java:31: cannot find symbol
    symbol : method doublevalue()
    location: class java.lang.Double
    double dv = r1.doublevalue();
    ^
    4 errors

    1. Vector vect = new Vector();
      vect.addElement(10);

      The above code gives error if you run below JDK 1.5. From JDK 1.5, it works. Why?

      DS of Java accepts only objects (of any class). But 10 is primitive data type and not object. It is the cause error. From JDK 1.5, 10 is converted into object (of Integer) automatically. This is known autoboxing.

      1. The code above errors if you run JDK = 1.5):
        public void doNumsNewWay() {
        ArrayList listOfNumbers = new ArrayList();
        listOfNumbers.add(3);
        int num = listOfNumbers.get(0);
        }

        See the difference?
        Cheers, hope this was usefull.

  9. sir,is it necessary to create as much as wrapper class objects as much number of variables of any datatype in the program….like can access all variable of same type by declaring only one object for all of them..
    thanks

  10. Hi Sir,

    its very useful and very good explanation.
    Sir I have a Question regards wrapper classes,
    I have to retrieve data from tables in sql using wrapper classes in java?
    How could I do this please reply sir.

  11. please explain me the use of tis code

    int marks = 50;
    Integer m1 = new Integer(marks);

    why we are creating object for that and what is the use of it? /
    please clarify me with small situation that we have to pass use m1 instead of marks.

      1. Hello sir,
        I understood the point but i still didn’t get use of it.
        When we put values in DS, we directly can put them without converting into any object. Can you please help me out. ..I have my exams (12 board) from 9 feb

  12. class a
    {
    public static void main(String… a)
    {
    Integer p=10;
    Short s=10;
    System.out.println(s);
    System.out.println(p);
    System.out.println(p.equals((Integer)s));
    }
    }

    in this code here it is showing compile time error i had tried y this happen then i got know that just becoz these classes are immutable

    but in this below program v are easily doing type cast can you tell me sir how this happen and y its result showing “null”

    import java.util.*;
    class a
    {
    public static void main(String… a)
    {
    String ab=”10″;
    Map m= new HashMap();
    Integer i=new Integer(10);
    System.out.println((Integer)m.get(ab));
    }
    }

Leave a Comment

Your email address will not be published.