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 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:
- Byte class holds byte variable
- Short class holds short variable
- Integer class holds int variable
- Long class holds long variable
- Float class holds float variable
- Double class holds double variable
- Character class holds char variable
- 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); } } }