Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in java is there a wrapper for every primitive type

Tags:

The Number subclasses wrap primitive numeric types (Byte, Integer, Double, Float, Long, and Short).

What purpose do they serve?

like image 221
Saurabh Kumar Avatar asked Jan 18 '12 19:01

Saurabh Kumar


People also ask

Why does Java have wrapper classes for primitive types?

Wrapper Class will convert primitive data types into objects. The objects are necessary if we wish to modify the arguments passed into the method (because primitive types are passed by value). The classes in java. util package handles only objects and hence wrapper classes help in this case also.

Does every primitive type have a wrapper class?

Each primitive type has a corresponding wrapper: byte, short, int, long, float, double, boolean, char.

Why is type wrapper needed in Java?

Wrapper classes are fundamental in Java because they help a Java program be completely object-oriented. The primitive data types in java are not objects, by default. They need to be converted into objects using wrapper classes.


2 Answers

Those wrapper classes were created so that there was some way to use those primitive types with various container classes like ArrayList. Since primitive types can't directly be coerced into Object references, they are stored in wrapper classes to allow them to be used where Object references are required.

like image 77
recursive Avatar answered Sep 22 '22 12:09

recursive


Because the wrappers are Objects.

  • Collections needs Objects
  • Objects can be instantiated to null
  • We can get NullPointerException instead of strange behavior if you for example instantiate to -1 in a primitive
  • The "wrapper" has convenient methods
like image 27
Farmor Avatar answered Sep 24 '22 12:09

Farmor