Wrapper Class in Java

Wrapper classes provide object methods for the eight primitive data types in Java. If a method expects an Object but programmer needs to send in a primitive data type, it can only be achieved by using Wrapper Classes in Java. For example, if you want to store a mapping between an integer value 50 (int i = 50) to an Object wrapper classes must be used.


 
Ads

Wrapper Classes provide object methods for the eight primitive data types in Java. If a method expects an Object but programmer needs to send in a primitive data type, it can only be achieved by using Wrapper Classes in Java. For example, if you want to store a mapping between an integer value 50 (int i = 50) to an Object wrapper classes must be used.

Wrapper classes are part of java.lang package that defines the eight primitive data types in Java. We need Wrapper classes:

  • To use null value
  • To use in a Collection
  • When Object is required

Wrapper Classes and their corresponding primitive data types in Java are:

  1. Byte class holds byte variable
  2. Short class holds short variable
  3. Integer class holds int variable
  4. Long class holds long variable
  5. Float class holds float variable
  6. Double class holds double variable
  7. Character class holds char variable
  8. Boolean class holds boolean variable

For example primitive data type int can be defined as:

int i = 10;

*Here ?i? is a variable that holds the value 10.

Whereas, object of a Wrapper Integer class can be created as:

Integer j = new Integer (10);

*Here ?j? is an object variable that holds a reference to an object. The value of object ?j? can only be accessed using the methods of the Integer class.    For example:

int z = i + j.intValue();

Example of Wrapper Class in Java:

  • How to insert an element at the specified position using the add(int, Object) method:
import java.util.*;
public class VecAdd{
  public static void main(String argv[]){
  Vector v = new Vector();
  v.add(0,new Integer(10));
  v.add(1,new Integer(20));
  v.add(2,new Integer(30));
  v.add(3,new Integer(40));
    v.add(4,new Integer(50));
  v.add(5,new Integer(60));
  for(int i=0; i < v.size();i ++){
  Integer iw =(Integer) v.get(i);
  System.out.println(iw);
  }
  }
}

Advertisements

Share on Google+Share on Google+

Wrapper Class in Java

Posted on: April 23, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: Wrapper Class in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads