×

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

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.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

flour pack problem in Java

Create a method called canPack and give it three int parameters: bigCount, smallCount, and objective. The bigCount option indicates the number of large flour bags (5 kilos each). The smallCount argument indicates...

3 minutes read.

Java String replaceAll() method

Java String replaceAll() method returns a String replacing all the sequence of characters matching regular expression i.e regex and replacement string. Syntax: public String replaceAll(String regex, String replacement) Parameters: regex : regular expression replacement :...

1 minute read.

How to Convert int to long in Java

How to Convert int to long in Java When two variables of different types are involved in the single expression, Java compiler uses built-in library function to convert the variable to...

2 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute 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.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Heap Space Out of Memory Error

This error is called an "out of memory" error, which indicates that the JVM cannot allocate an object in memory from the heap. Hence the java.lang.out of memory error, describing...

2 minutes read.

Java Get File Size

There are three ways to get the file size in Java. Using Java InputOutput Using NewInputOutput Library Files.size() Method FileChannel.size() Method Using Apache Commons InputOutput Using Java InputOutput: The Java IO package offers the classes that deal...

5 minutes read.

Nth Term of Geometric Progression in Java

There are 3 numbers provided. The geometric progression's initial term is the first number. The second number is the geometric progression's common ratio, and the third number represents the nth...

3 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Java Math with Methods and Examples

Java Math class contains various methods for performing math operations like min(), max(), avg() and various trigonometric functions like sin(), cos(), tan() etc. Methods: The java.lang.Math class contains various methods for performing...

5 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.