Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Benefits of using wrapper classes over primitives in Java

Tags:

java

wrapper

At a very abstract level I do know that wrapper classes, create an object of the primitive data type but I was curious as to why do we need to use wrapper classes and what benefits do they offer over primitive data types.

like image 200
veepsk Avatar asked Dec 22 '12 01:12

veepsk


3 Answers

Collections in the first place, for example,List<Integer>, you cannot use primitive int here. Actually any generic class / interface that can work with different object types like

public interface Callable<V> {
    V call() throws Exception;
}

Note that wrapping is best done using not new Integer(i) but Integer.valueOf(i) the latter will try to use cache. Unwrapping is done as Integer.intValue(). These wrapping / unwrapping of primitives are so typical operations that Java 5 introduced autoboxing / unboxing

List<Integer> list = new ArrayList<>();
list.add(1);
int i = list.get(0);

this code is automatically converted by Java compiler into

list.add(Integer.valueIf(1));
int i = list.get(0).intValue();    // this is where NullPointerException sometimes happens
like image 83
Evgeniy Dorofeev Avatar answered Sep 18 '22 23:09

Evgeniy Dorofeev


Wrapper classes are designed to add more functionality to the primitive types, so that they are compatible with generic code, using the Collection Framework, and many other benefits. However, they are not mean't to replace primitive types.

So, you should use wrappers only when necessary, such as when dealing with generics, because creating an object adds substantial overheads to your program. So, in normal cases, you should stick to primitives.

like image 34
JavaNewbie_M107 Avatar answered Sep 18 '22 23:09

JavaNewbie_M107


A wrapper type enables a primitive to hold more contextual meaning. For instance an integer could be anything, whereas a class called Hours, for example, gives the number meaning wherever it is used.

They also enable methods to be written that mutate the said primitive in a consistent and obvious way to consumers. Have a look at Domain Driven Design for more information surrounding this point.

like image 20
Rich O'Kelly Avatar answered Sep 20 '22 23:09

Rich O'Kelly