Open In App

Wrapper Classes in Java

Last Updated : 29 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Wrapper class in Java is a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Let’s check on the wrapper classes in Java with examples:

Need of Wrapper Classes

There are certain needs for using the Wrapper class in Java as mentioned below:

  1. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).
  2. The classes in java.util package handles only objects and hence wrapper classes help in this case also.
  3. Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.
  4. An object is needed to support synchronization in multithreading.

Advantages of Wrapper Classes

  1. Collections allowed only object data.
  2. On object data we can call multiple methods compareTo(), equals(), toString()
  3. Cloning process only objects
  4. Object data allowed null values.
  5. Serialization can allow only object data.

Below are given examples of wrapper classes in Java with their corresponding Primitive data types in Java.

Primitive Data Types and their Corresponding Wrapper Class

Primitive Data Type

Wrapper Class

                                   char                                   

                               Character                              

byte

Byte

short

Short

int 

Integer

long

Long

float

Float

double

Double

boolean 

Boolean

Autoboxing and Unboxing

1. Autoboxing

The automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double, etc. 

Example:

Java
// Java program to demonstrate Autoboxing

import java.util.ArrayList;
class Autoboxing {
    public static void main(String[] args)
    {
        char ch = 'a';

        // Autoboxing- primitive to Character object
        // conversion
        Character a = ch;

        ArrayList<Integer> arrayList
            = new ArrayList<Integer>();

        // Autoboxing because ArrayList stores only objects
        arrayList.add(25);

        // printing the values from object
        System.out.println(arrayList.get(0));
    }
}

Output
25

2. Unboxing

It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc. 

Example:

Java
// Java program to demonstrate Unboxing
import java.util.ArrayList;

class Unboxing {
    public static void main(String[] args)
    {
        Character ch = 'a';

        // unboxing - Character object to primitive
        // conversion
        char a = ch;

        ArrayList<Integer> arrayList
            = new ArrayList<Integer>();
        arrayList.add(24);

        // unboxing because get method returns an Integer
        // object
        int num = arrayList.get(0);

        // printing the values from primitive data types
        System.out.println(num);
    }
}

Output
24

Java Wrapper Classes Example

Java
// Java program to demonstrate Wrapping and UnWrapping
// in Classes
import java.io.*;

class GFG {
    public static void main(String[] args)
    {
        // byte data type
        byte a = 1;

        // wrapping around Byte object
        Byte byteobj = new Byte(a);
        // Use with Java 9
        // Byte byteobj = Byte.valueOf(a);

        // int data type
        int b = 10;

        // wrapping around Integer object
        Integer intobj = new Integer(b);
        // Use with Java 9
        // Integer intobj = Integer.valueOf(b);

        // float data type
        float c = 18.6f;

        // wrapping around Float object
        Float floatobj = new Float(c);
        // Use with Java 9
        // Float floatobj = Float.valueOf(c);

        // double data type
        double d = 250.5;

        // Wrapping around Double object
        Double doubleobj = new Double(d);
        // Use with Java 9
        // Double doubleobj = Double.valueOf(d);

        // char data type
        char e = 'a';

        // wrapping around Character object
        Character charobj = e;

        // printing the values from objects
        System.out.println(
            "Values of Wrapper objects (printing as objects)");
        System.out.println("\nByte object byteobj: "
                           + byteobj);
        System.out.println("\nInteger object intobj: "
                           + intobj);
        System.out.println("\nFloat object floatobj: "
                           + floatobj);
        System.out.println("\nDouble object doubleobj: "
                           + doubleobj);
        System.out.println("\nCharacter object charobj: "
                           + charobj);

        // objects to data types (retrieving data types from
        // objects) unwrapping objects to primitive data
        // types
        byte bv = byteobj;
        int iv = intobj;
        float fv = floatobj;
        double dv = doubleobj;
        char cv = charobj;

        // printing the values from data types
        System.out.println(
            "\nUnwrapped values (printing as data types)");
        System.out.println("\nbyte value, bv: " + bv);
        System.out.println("\nint value, iv: " + iv);
        System.out.println("\nfloat value, fv: " + fv);
        System.out.println("\ndouble value, dv: " + dv);
        System.out.println("\nchar value, cv: " + cv);
    }
}

Output
Values of Wrapper objects (printing as objects)

Byte object byteobj: 1

Integer object intobj: 10

Float object floatobj: 18.6

Double object doubleobj: 250.5

Character object charobj: a

Unwrapped values (printing as data types)

byte value, bv: 1

int value, iv: 10

float value, fv: 18.6

double value, dv: 250.5

char value, cv: a

Custom Wrapper Classes in Java

Java Wrapper classes wrap the primitive data types. We can create a class that wraps data inside it. So let us check how to create our own custom wrapper class in Java. It can be implemented for creating certain structures like queues, stacks, etc.

Example:

Java
// Java Program to implement
// Custom wrapper class
import java.io.*;

// wrapper class
class Maximum {
    private int maxi = 0;
    private int size = 0;

    public void insert(int x)
    {
        this.size++;
        if (x <= this.maxi)
            return;
        this.maxi = x;
    }

    public int top() { return this.maxi; }

    public int elementNumber() { return this.size; }
};

// 
class GFG {
    public static void main(String[] args)
    {
        Maximum x = new Maximum();
        x.insert(12);
        x.insert(3);
        x.insert(23);

        System.out.println("Maximum element: " + x.top());
        System.out.println("Number of elements inserted: "
                           + x.elementNumber());
    }
}

Output
Maximum element: 23
Number of elements inserted: 3

Wrapper Classes in Java – FAQs

Which are the wrapper classes in Java?

A Wrapper class in Java is a class whose object wraps or contains primitive data types.

Why use the wrapper class in Java?

The wrapper class in Java is used to convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method.

What are the 8 wrapper classes in Java?

There are 8 Wrapper classes in Java these are Boolean, Byte, Short, Character, Integer, Long, Float, Double.



Previous Article
Next Article

Similar Reads

Utility Methods of Wrapper Classes in Java
Prerequisite: Wrapper Classes The objective of the Wrapper class is to define several utility methods which are required for the primitive types. There are 4 utility methods for primitive type which is defined by the Wrapper class: 1. valueOf() method: We can use the valueOf() method to create a Wrapper object for a given primitive or String. There
4 min read
Sorting Elements of Arrays and Wrapper Classes that Already Implements Comparable in Java
Java provides the Comparable interface to sort objects using data members of the class. The Comparable interface contains only one method compareTo() that compares two objects to impose an order between them. It returns a negative integer, zero, or positive integer to indicate if the input object is less than, equal to, or greater than the current
4 min read
Need of Wrapper Classes in Java
Firstly the question that hits the programmers is when we have primitive data types then why does there arise a need for the concept of wrapper classes in java. It is because of the additional features being there in the Wrapper class over the primitive data types when it comes to usage. These methods include primarily methods like valueOf(), parse
3 min read
Different Ways to Create the Instances of Wrapper Classes in Java
Wrapper Class a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Methods: We can use two ways to construct the instance of the Wrapper Classes Usi
5 min read
Primitive Wrapper Classes are Immutable in Java
In Java, an immutable class is a class (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) which once created then its body can not be changed and the same applies to immutable objects which once created cannot be changed. Now the question arises that we do need the help of wrapper classes while dealing with primitive data types in
3 min read
Java I/O Operation - Wrapper Class vs Primitive Class Variables
It is better to use the Primitive Class variable for the I/O operation unless there is a necessity of using the Wrapper Class. In this article, we can discuss briefly both wrapper class and primitive data type. A primitive data type focuses on variable values, without any additional methods.The Default value of Primitive class variables are given b
3 min read
Compute modulus division by a power-of-2-number using Wrapper Class
Prerequisite : Compute modulus division by a power-of-2-number Now as you know for getting n modulus 2k, we just need to return k bits(from LSB) in binary representation of n. In Java, you can use Wrapper class toBinaryString() method to get binary string representation of a number and getting substring from (str.length()-k) to end. And then by usi
2 min read
Catching Base and Derived Classes as Exceptions in C++ and Java
An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. Let's discuss what is Exception Handling and how we catch base and derived classes as an exception in C++: If both base and derived classes are caught as exceptions, then the catch
4 min read
Nested Classes in Java
In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation and creates more readable and maintainable code. The scope of a nested class is bounded by the scope of its enclosing class
5 min read
Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have?
Prerequisite: Interface and Abstract class in Java. A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created. Why interfaces can not have the constructor? An Interface is a complete abstraction of class. All data members present in the interface are by de
4 min read
Commonly Used Methods in LocalDate, LocalTime and LocalDateTime Classes in Java
Java provides the three most important classes related to dates namely LocalDate, LocalTime, LocalDateTime which makes the handling of dates in Java very easy as in order to use these classes, we need to import 'java.time' package which is main the main API for dates, times, instants, and durations. Illustration: 1. java.time.* // To include all cl
5 min read
Random vs ThreadLocalRandom Classes in Java
The Random Class of the java.util package is used for generating a stream of pseudorandom numbers. It uses a 48-bit seed, which is amended by implementing a Linear Congruential Formula. The general form of a Linear Congruential Formula is an+1 = k * an + c (mod m) where a0 is the seed, a1, a2, ... an, an+1 are the random numbers and k, c, m are con
5 min read
Java - Divide the Classes into Packages with Examples
Let us first know what is a class and package in Java. Class in java is a model for creating objects. It means that the properties and actions of the objects are written in class. Properties are represented by variables and actions of the objects are represented by methods. So, a class contains variables and methods. The same variables are also ava
6 min read
How to Create Different Packages For Different Classes in Java?
Let us first know what is a class and package in Java. Class in java is a model for creating objects. It means that the properties and actions of the objects are written in class. Properties are represented by variables and actions of the objects are represented by methods. So, a class contains variables and methods. The same variables are also ava
6 min read
How to Access Inner Classes in Java?
In Java, inner class refers to the class that is declared inside class or interface which were mainly introduced, to sum up, same logically relatable classes as Java is purely object-oriented so bringing it closer to the real world. It is suggested to have adequate knowledge access the inner class, first create an object of the outer class after th
3 min read
Different Types of Classes in Java with Examples
A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: Modifiers: A class can be public or has default accessclass keyword: class keyword is used to create a clas
11 min read
Method Overloading in Different Classes in Java
Methods of a class said to be overloaded if Both declared in the same class, orBoth inherited by a class, orOne declared and one inherited And have the same name but a different signature. Refer to this article, Different ways of Method Overloading in Java, for a basic understanding of method overloading. The below programs demonstrate the same. Ca
3 min read
Static Control Flow with Inherited Classes in Java
Before understanding the static control flow of a program, we must be familiar with the following two terms: Class loading: It refers to reading the .class file and loading it into the memory(JVM). Java loads classes dynamically, that is, classes are loaded on demand only when they are referred.Class initialization: It refers to executing and initi
6 min read
Java Unnamed Classes and Instance Main Methods
Java has introduced a significant language enhancement in Java Enhancement Proposal (JEP) 445, titled "Unnamed Classes and Instance Main Methods". This proposal aims to address the needs of beginners, making Java more accessible and less intimidating. Let's delve into the specifics of this proposal and understand how it simplifies the learning curv
7 min read
Access modifiers for classes or interfaces in Java
In Java, methods and data members can be encapsulated by the following four access modifiers. The access modifiers are listed according to their restrictiveness order. 1) private (accessible within the class where defined) 2) default or package-private (when no access modifier is specified) 3) protected (accessible only to classes that subclass you
1 min read
Private Constructors and Singleton Classes in Java
Let's first analyze the following question: Can we have private constructors ? As you can easily guess, like any method we can provide access specifier to the constructor. If it's made private, then it can only be accessed inside the class. Do we need such 'private constructors ' ? There are various scenarios where we can use private constructors.
2 min read
Output of Java program | Set 15 (Inner Classes)
Prerequisite :- Local inner classes , anonymous inner classes 1) What is the output of the following java program? public class Outer { public static int temp1 = 1; private static int temp2 = 2; public int temp3 = 3; private int temp4 = 4; public static class Inner { private static int temp5 = 5; private static int getSum() { return (temp1 + temp2
3 min read
Types of Classes in Java
A class is a blueprint in the Java programming language from which an individual object can be built. In Java, we may declare a class by using the class keyword. Class members and functions are declared simply within the class. Classes are required for the creation of Java programs. The object-oriented paradigm (OOP) allows users to describe real-w
8 min read
Understanding Classes and Objects in Java
The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporate both data and behavior. Hence, Object-oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rules. Programs are organized around objects rather t
10 min read
Classes and Objects in Java
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior. For example, the animal type Dog is a class while a particular dog named Tommy is an object of the Dog class. In this artic
11 min read
Messages, aggregation and abstract classes in OOPS
Object-Oriented Programming System (OOPS) is the basic concept of many programming languages. It is a paradigm based on the object which contains methods and data. This concept is used to make programming a class and object model which behaves like a real-world scenario. In this article, we'll learn about messages, aggregation, composition and abst
5 min read
How to Create Classes in Android Studio?
In Android during the project development most of the time there is a need for classes in the projects. For example, in the case of CRUD operation, we need a model class to insert and retrieve data. Also to hold the info in our custom view we need to create a getter setter class. So basically in android, there are two types of classes we can create
3 min read
Hibernate - Generator Classes
Hibernate is an open-source, non-invasive, lightweight java ORM(Object-relational mapping) framework that is used to develop persistence logic that is independent of Database software. In JDBC to develop persistence logic, we deal with primitive types. Whereas in Hibernate framework we use Objects to develop persistence logic that is independent of
5 min read
Hibernate - Create POJO Classes
POJO stands for Plain Old Java Object. In simple terms, we use POJO to make a programming model for declaring object entities. The classes are simple to use and do not have any restrictions as compared to Java Beans. To read about POJO classes and Java Bean refer to the following article - POJO classes and Java Bean POJO is handier as its best in r
3 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Article Tags :
Practice Tags :