Wrapper Class


Wrapper classes provide a way to use primitive data types (int, boolean, etc.) as objects. The table shows the primitive types and the equivalent wrapper classes. Sometimes you must use wrapper classes, for example, when working with collection objects, such as ArrayList, where primitive types cannot be used (the list can only store objects):
Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
   // Invalid: no primitive type to be used for ArrayList
   ArrayList<int>     myNumbers = new ArrayList<int>( );
   // Valid: Interger, a wrapper class of int
   ArrayList<Integer> myNumbers = new ArrayList<Integer>( );
ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. It may be slower than standard arrays, but can be helpful in programs where intensive manipulation of the arrays is needed.

ArrayLst.java (the ArrayList class)

 // Demonstration of the class ArrayList
 import java.io.*; 
 import java.util.*; 

 class ArrayLst {
   public static void main( String[ ] args ) throws IOException { 
     // Size of ArrayList 
     int n = 5; 
     // Declaring ArrayList with initial size n 
     ArrayList<Integer> arrLst = new ArrayList<Integer>( n ); 

     // Appending the new element at the end of the list
     for ( int i=1; i<=n; i++ ) arrLst.( i ); 

     // Removing element at index 3 
     arrLst.( 3 ); 

     // Displaying ArrayList after deletion 
     System.out.print( arrLst ); 
     // Printing elements one by one 
     for ( int i=0; i<arrLst.size( ); i++ )
       System.out.print( " " + arrLst.( i ) ); 
   }
 }
shell> java ArrayLst     ⇒     Output: [1, 2, 3, 5] 1 2 3 5

        Result: