Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapper class in java [closed]

Tags:

java

What is the use of wrapper class? I can't understand the wrapping thing in this topic. It wraps primitive data types but for what and how it wraps? When they tell wrapping what does it really mean?

like image 539
Sumithra Avatar asked Dec 22 '22 22:12

Sumithra


2 Answers

As you are aware, In Java not everything is an Object. There are primitive types such as int ,double float etc. So if you wanted to use a primitive type in place of Object i.e. if a method expects an Object but you need to send in a primitive type, without Wrapper classes this wouldn't be possible. Take for instance the Map interface. The put(Object,Object) method takes Objects as both key and value. If you, for example wanted to store a mapping between an integer value 1 (int i=1) to an Object, without wrapper classes this wouldn't be possible. Wrapper classes are used to represent primitive values when an object is required.

like image 198
Suresh Kumar Avatar answered Jan 15 '23 18:01

Suresh Kumar


The general idea of a wrapper class is a class that, for lack of a better term, 'boxes' another class or some other functionality. This could be done to abstract the wrapped items, and expose a simpler interface to the user.

I think your specific question concerns the Java Primitive Wrapper Classes, which are classes that represent the primitive types (int, double, boolean, byte, and so on) as classes. One of the reasons for this is they are used for when Object types are needed and you want to use primitives, like when using any class in java.Collections.

like image 21
逆さま Avatar answered Jan 15 '23 20:01

逆さま