- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why do we need a wrapper class in Java?
A Wrapper class is a class which contains the primitive data types (int, char, short, byte, etc). In other words, wrapper classes provide a way to use primitive data types (int, char, short, byte, etc) as objects. These wrapper classes come under java.util package.
Why we need Wrapper Class
- 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.
- Data structures in the Collection framework such as ArrayList and Vector store only the objects (reference types) and not the primitive types.
- The object is needed to support synchronization in multithreading.
Implementation of the wrapper class in Java
Autoboxing in Wrapper Class
Autoboxing is used to convert primitive data types into corresponding objects.
Example
public class AutoBoxingTest { public static void main(String args[]) { int num = 10; // int primitive Integer obj = Integer.valueOf(num); // creating a wrapper class object System.out.println(num + " " + obj); } }
Output
10 10
Unboxing in Wrapper Class
Unboxing is used to convert the Wrapper class object into corresponding primitive data types.
Example
public class UnboxingTest { public static void main(String args[]) { Integer obj = new Integer(10); // Creating Wrapper class object int num = obj.intValue(); // Converting the wrapper object to primitive datatype System.out.println(num + " " + obj); } }
Output
10 10
- Related Articles
- Why do we need generics in Java?
- Why do we need inner classes in Java?
- Why do we need a Database
- Why do we need KDD?
- Why do we need Energy?
- Why do we need weakMaps in Javascript?
- Why do we need Good Manners?
- Why do we need Computer Networks?
- Why do we need shell scripting?
- Why do we need Data Encryption?
- Why do we need a separate Data Warehouse?
- Why do we need private methods in an interface in Java 9?
- Java Float Wrapper Class
- Why do we need a copy constructor and when should we use a copy constructor in Java?
- Why do we need to study Physics?

Advertisements