×

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 Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

Java Buffer Reader

When a variable cannot change its value during run time is called a Static way of programming. In this programming, a variable is directly assigned to a value. Program: Import java.io.*; class  A {  ...

4 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

What is the ambiguity problem in Java?

The ambiguity problem in Java occurs when a method or constructor is overloaded with two or more methods with the same name but different parameters. This can confuse when multiple...

6 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.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Java IO

It is a part of java libraries but is often known as I/O streams, file I/O, and file handling. The Java I/O concept satisfies the need for input processing and...

4 minutes read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

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 File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

Java RMI

What is RMI in Java? A framework for developing distributed Java applications is provided by the RMI (Remote Method Invocation) API. An object can call methods on an object running in...

4 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 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.