Sunday, October 28, 2018

Wrapper class in java - example

f the main advantages of wrapper class is avoiding explicit type casting for primitive types while using collections.

Here is a basic example which will give compilation errors without explicit casting as shown below.


You can correct the program by adding type casting and here is a working sample

public class WrapperClassInJava {


 public static void main(String[] args) {

  List intList = new ArrayList();

  intList.add(123);

  int value= (int)intList.get(0);

 }

}


To avoid this explicit casting wrapper, we can add wrapper class as a generic argument to the collection.
eg: List<Integer> intList = new ArrayList<Integer>();

With this declaration of wrapper class, you can avoid explicit type casting. This example might not make good sense as we are declaring the list ourselves but when we are working with numerous lists in a big project, you can find lot of instances where avoiding explicit type casting is very useful and using wrapper classes save us from type casting exceptions.

public class WrapperClassInJava {

 public static void main(String[] args) {

  List<Integer> intList = new ArrayList<Integer>();

  intList.add(123);

  int value= intList.get(0);

  System.out.println(value);

 }
}

One more advantage is - as you are declaring Integer wrapper class as a generic argument, while coding adding any other wrapper class value to the list will give you a compilation error.

Another useful feature used with wrapper classes is unboxing.

int value= intList.get(0); // here hava compiler will unbox Integer wrapper class value to int premitive type

No comments:

Post a Comment