Wrapper classes

Wrapping and Unwrapping

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

In the above statement, an int data type marks is given an object form m1 just by passing the variable to the constructor of Integer class. Wherever, marks is required as an object, m1 can be used.

After using the Integer object in programming, now the programmer may require back the data type, as objects cannot be used in arithmetic operations. Now the object m1 should be unwrapped.

int iv = m1.intValue();

For unwrapping, the method intValue() of Integer class used. The int value iv can be used in arithmetic operations.

Parsing Operations

The other usage of wrapper classes is converting strings into data types. Sometimes, in programming, the programmer retrieves data in the form of strings. Data types are retrieved as strings. For example, the readLine() method of BufferedReader returns a string always of any data type it reads, command-line arguments are retrieved as strings and a text field in GUI gets a string. All these strings should be converted back to data types to use in arithmetic operations. The following program illustrates.

public class ParsingDemo
  public static void main(String args[])
    String price ="100";                 // declare some strings
    String rate = "5.8f";
    String tax ="50.2";
                                         // performing parsing operations on strings	
    int x = Integer.parseInt(price);
    float f1 = Float.parseFloat(rate);
    double y = Double.parseDouble(tax);

    System.out.println("\nPrinting data type values after parsing");
    System.out.println("int value: " + x);
    System.out.println("float value: " + f1);
    System.out.println("double value: " + y);
            // another style of converting strings into data types, very less used               
    Integer i1 = new Integer(price);
    Float f2 = new Float(rate);
    Double d1 = new Double(tax);
	    // extracting data types from wrapper objects
    int x1 = i1.intValue();
    float f3 = f2.floatValue();
    double d2= d1.doubleValue();
    System.out.println("\nPrinting data type values after conversion");
    System.out.println("int value: " + x1);
    System.out.println("float value: " + f3);
    System.out.println("double value: " + d2);

String price = "100";
int x = Integer.parseInt(price);

parseInt() is a static method of java.lang.Integer class that takes a string as parameter and returns an int value corresponding to the string. Similarly, the methods parseFloat(), parseDouble() of Float and Double classes return float and double values. This style of conversion is mostly used in coding. There is another way of converting strings to data types, but is less used. Following is the other way.

String price ="100";
Integer i1 = new Integer(price);
int x1 = i1.intValue();

Pass the string, price, to the constructor of Integer class. Now the price is represented as i1, an object of Integer class. From object i1, extract the int value with intValue() method of Integer class. Similarly, there exists methods like floatValue() and doubleValue() of classes Float and Double that return a float value and double value.

Now finally, you can observe that, a string value can be converted to a data type in two ways – using parseInt() method and using intValue() method; both belonging to Integer class.

The next program is another example on string conversions into all data types. Two styles of conversions are given.

  1. Using parsing operation (1st way)
  2. Using xxxValue() method wrapper classes (2nd way)
public class Conversions
  public static void main(String args[])
  {                                     // converting string to byte
    String str2 = "10"; 		// 1st way
    byte b1 = Byte.parseByte(str2);
    System.out.println(b1*b1);          // prints 100
					// 2nd way
    Byte by1 = new Byte(str2);
    byte b2 = by1.byteValue();                                         
    System.out.println(b2*b2);          // prints 100           

                                        // converting string to short
    short s1 = Short.parseShort(str2);  // 1st way
    System.out.println(s1*s1);          // prints 100
    Short sh1 = new Short(str2);	// 2nd way
    short s2 = sh1.shortValue();                                         
    System.out.println(s2*s2);          // prints 100           

                                        // converting string to int

    int i1 = Integer.parseInt(str2);	// 1st way
    System.out.println(i1*i1);          // prints 100

    Integer in1 = new Integer(str2);	// 2nd way
    int i2 = in1.intValue();                                         
    System.out.println(i2*i2);          // prints 100           

                                        // converting string to long

    long l1 = Long.parseLong(str2);	// 1st way
    System.out.println(l1*l1);          // prints 100
    Long lo1 = new Long(str2);		// 2nd way
    long l2 = lo1.longValue();                                         
    System.out.println(l2*l2);          // prints 100           

                                        // converting string to float

    String str3 = "10.5f";       	// 1st way
          // or it can be String str3 = "10.5";  
    float f1 = Float.parseFloat(str3);
    System.out.println(f1*f1);          // prints 110.25
    Float fl1 = new Float(str3);        // 2nd way
    float f2 = fl1.floatValue();
    System.out.println(f2*f2);          // prints 110.25

                                        // converting string to double

    String str4 = "10.5";   		// 1st way
    double d1 = Double.parseDouble(str4);
    System.out.println(d1*d1);          // prints 110.25
    Double do1 = new Double(str4);	// 2nd way
    double d2 = do1.doubleValue();
    System.out.println(d2*d2);          // prints 110.25

                       // converting string to character

    String str1 = "A";
    char ch1 = str1.charAt(0);
    System.out.println(ch1);            // prints A

                       // converting string to boolean

    String str5 = "true";               // 1st way
    boolean b3 = Boolean.parseBoolean(str5);
                                        // 2nd way
    Boolean bo1 = new Boolean(str5);
    boolean b4 = bo1.booleanValue();

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 ?)

    Integer In =10;
    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();

    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();

      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();
        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..

  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;

    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);

Leave a Comment

Your email address will not be published. Required fields are marked *