×

Java Wrapper Class

Wrapper class in Java encapsulates a primitive type within an object. In other words, it is a unique mechanism of Java to convert primitive type in to object and object into primitive type.

The type wrapper classes are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. They offer a wide range of methods that allows us to integrate primitive data type into Java’s object hierarchy completely.

Uses of Wrapper class

  • It is used to convert the primitive data type into objects.
  • Classes in “Java.util” package deals only with objects, so in this the wrapper classes plays its role.
  • We convert the primitive value to object using wrapper class because we need to convert the objects into streams to perform the serialization.
  • Synchronization in Java works with objects in multithreading. Therefore it is required to convert the value into objects.
  • The Collection framework in Java works with objects only.

The corresponding type wrapper class for the primitive type is in below table:

Primitive Type Wrapper class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

As you can see in the above table, the primitive types are written in lower case. But the wrapper class’s first letter is capital. So always use them as given above. Each Wrapper classes are briefly explained below:

The Numeric Type Wrappers

The numeric type wrappers are mostly used. These are Byte, Short, Integer, Long, Float, and Double. All the type wrappers inherit the abstract class Number. Below are the methods that are declared by Number class which returns the value of an object in different number formats.

bytebyteValue()

doubledoubleValue()

floatfloatValue()

intintValue()

longlongValue()

shortshortValue()

Character Type Wrapper

It is a wrapper class for char. The constructor for Character is Character(char ch).

Here, ch denotes the character that will be wrapped by the Character object being created. To get the char value contained in a Character object, we need to call charValue() as show here:

charcharValue().

Boolean Type Wrapper

It is a wrapper class for boolean values. The constructor for boolean are:

Boolean(booleanboolValue)-boolValue must be either true or false.

Boolean(String boolString)-if boolString contains the string “true”, then the new Boolean object will be true else it will be false.

Autoboxing and Auto-unboxing

From JDK 5, Java added two other features: autoboxing and auto-unboxing. The process of automatically encapsulating primitive type into its equivalent type wrapper whenever an object type is needed is called Autoboxing. Whereas, the process by which the value of a boxed object is automatically unboxed from a type wrapper, when its value is needed is called as Auto-unboxing.

It also helps prevent errors by making ease of coding for several algorithms and removes the vulnerabilities of manually boxing and unboxing.

Example to demonstrate autoboxing/unboxing :

Class AutoboxDemo
 {
             public static void main (String args[])
             {
                         Integer first = 10; //autoboxing an int
                         inti = first; //auto-unboxing
                         System.out.println(i + " " + first); 
             }
 } 
 classWrapperDemo
 { 
 publicstaticvoid main(String args[]) 
     { 
 byte a = 10; 
 int b = 20; 
 float c = 20.5f; 
 char e='a'; 
 double d = 25.5;
         //autoboxing
         Byte byteobj = newByte(a);
         Integer intobj = newInteger(b); 
         Double doubleobj = newDouble(d); 
         Character charobj=e; 
         Float floatobj = new Float(c); 
         //printing the values from objects 
 System.out.println("---Values of objects (printing as objects)---"); 
 System.out.println("Byte object-byteobj:  " + byteobj); 
 System.out.println("Integer object-intobj:  " + intobj); 
 System.out.println("Float object-floatobj:  " + floatobj); 
 System.out.println("Double object-doubleobj:  " + doubleobj); 
 System.out.println("Character object-charobj:  " + charobj); 
         //un-boxing 
 bytebv = byteobj; 
 int iv = intobj; 
 floatfv = floatobj; 
 double dv = doubleobj; 
 char cv = charobj; 
         // printing the values from data types 
 System.out.println("---Printing primitive values---"); 
 System.out.println("byte value, bv: " + bv); 
 System.out.println("int value, iv: " + iv); 
 System.out.println("float value, fv: " + fv); 
 System.out.println("double value, dv: " + dv); 
 System.out.println("char value, cv: " + cv); 
     } 
 } 

Output:

---Values of objects (printing as objects)---
Byte object-byteobj:  10
Integer object-intobj:  20
Float object-floatobj:  20.5
Double object-doubleobj:  25.5
Character object-charobj:  a
---Printing primitive values---
byte value, bv: 10
int value, iv: 20
float value, fv: 20.5
double value, dv: 25.5
char value, cv: a 


Related Topics

Sublime Number in Java

In this tutorial, we will understand what is meant by sublime number in java. From the point of the coding interview, it is one of the important topics. We will we will...

4 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Salesman Problem in Java

The Traveling Salesman Problem determines the shortest path that visits each city approximately once and loops back to the starting location. Another Java problem that is most like the Traveling...

5 minutes read.

Java Math scalb() Method

The scalb() method of Java Math class returns a single perfectly rounded product of floating-point and member of the double value set as if performed by d*2scaleFacor rounded value. Syntax: public static...

2 minutes read.

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put...

6 minutes read.

Multithreading Program in Java

Multithreading Program in Java: Before discussing multithreading, it is important to discuss threads. Threads are the most fundamental part of a process. A process can have one or more threads....

4 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Set Matrix Zeros in Java

In coding round interviews, it is frequently asked as the most significant challenge. an m*n matrix is provided. Set the entire column and row of the matrix to 0 if any...

6 minutes read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Java Volatile Keyword

The compiler, runtime, or processors may use any kind of optimization if there aren't any required synchronizations. Although most of the time these improvements are advantageous, they occasionally can result...

6 minutes read.