×

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

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Concurrent Modification Exception In Java

When an object is attempted to be updated concurrently when it is not allowed, the ConcurrentModificationException arises. This error typically occurs while using Java Collection classes. When another thread is iterating...

5 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Java Math tanh() Method

The tanh() method of Java Math class returns the hyperbolic tangent of the specified double value. Syntax: public static double tanh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic tangent is to...

2 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

Java Binary to Hexadecimal

Converting between types in programming is an important task. Moving from one kind to another kind conversion is occasionally necessary. We have discussed numerous conversion types in the section on...

3 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Java Integer valueOf() method

The valueOf() method of Java Integer class returns an Integer object holding the specified int value. The second method returns an Integer object holding the specified String value. The third syntax returns...

2 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Java logger

Logging is a crucial Java feature that aids developers in identifying issues. The logging methodology is included with Java as the programming language. It offers the Logging API, which debuted...

7 minutes read.

Lazy loading in Java

Lazy loading is the idea of waiting to load an object until you need it. In other words, it is the practice of postponing class instantiation until it is necessary....

5 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Reverse a String using Collections in Java

Generally, a String is a grouping of characters. Yet, in Java, a String is an item that addresses a succession of characters. The Java.lang.String class is utilized to make a...

5 minutes read.