HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / Java Basics / Java Wrapper Classes – Autoboxing and Unboxing Example

Java Wrapper Classes – Autoboxing and Unboxing Example

In this Java Tutorial, learn about Java wrapper classes, their usage, conversion between primitives and objects; and autoboxing and unboxing with examples.

1. Java Wrapper Classes

In Java, we have 8 primitive data types. Java provides type wrappers, which are classes that encapsulate a primitive type within an Object.

  • A wrapper class wraps (encloses) around a primitive datatype and gives it an object appearance. Wherever the primitive datatype is required as an object type, this type wrapper can be used.
  • Wrapper classes include methods to unwrap the object and give back the data type.
  • The type wrappers classes are part of java.lang package.
  • Each primitive type has a corresponding wrapper class.
Primtive TypeWrapper Class
doubleDouble
floatFloat
longLong
intInteger
shortShort
byteByte
charCharacter
booleanBoolean

2. When to use Wrapper Classes

Java wrapper classes are used in scenarios –

  • When two methods wants to refer to the same instance of an primitive type, then pass wrapper class as method argument.
  • Java Generics works only with object and does not support primitive types.
  • Java Collections deal only with objects; to store a primitive type in one of these classes, you need to wrap the primitive type in a class.
  • When you want to refer null from data type, the you need object. Primitives cannot have null as value.

3. Conversions

3.1. Converting Primitive Type to Wrapper Class

There are two ways for converting a primitive type into an object of corresponding wrapper class –

  1. Using constrcutors
  2. Using static factory methods
// 1. using constructor
Integer object = new Integer(10);

// 2. using static factory method
Integer anotherObject = Integer.valueOf(10);

In above example, the valueOf() method is a static factory method that returns an instance of Integer class representing the specified int value.

Similarly, we can convert the other primitive types like boolean to Boolean, char to Character, short to Short, etc.

Java wrapper classes uses internal caching which returns internally cached values that makes wrapper classes more efficient in perfomance and memory unilization.

3.2. Converting Wrapper Class to Primitive Type

Converting from wrapper class to primitive type is simple. We can use the corresponding instance methods to get the primitive type. e.g. intValue(), doubleValue(), shortValue() etc.

Integer object = new Integer(10);

int val = object.intValue();	//wrapper to primitive

4. Autoboxing and Unboxing

Beginning with JDK 5, Java added two important features:

  • Autoboxing
  • Auto-Unboxing

4.1. Autoboxing

Autoboxing is the automatic conversion of the primitive types into their corresponding wrapper class.

For example, converting an int to an Integer, a char to a Character, and so on.

We can simply pass or assign a primitive type to an argument or reference accepting wrapper class type.

Java Autoboxing Example
Character ch = 'a';		//char to Character

List<Integer> integerList = new ArrayList<>();

for (int i = 1; i < 10; i ++) 
{
    integerList.add(i);		//int to Integer
}

In given example, integerList is a List of Integers. It is not a list of primitive type int values.

Here compiler automatically creates an Integer object from i and adds the object to integerList. Thus, the previous code turn into the following at runtime:

List<Integer> integerList = new ArrayList<>();

for (int i = 1; i < 50; i += 2) 
{
    integerList.add(Integer.valueOf(i));		//autoboxing
}

4.2. Unboxing

Unboxing happens when the conversion happens from wrapper class to its corresponding primitive type. It means we can pass or assign a wrapper object to an argument or reference accepting primitive type.

Java Unboxing Example
public static int sumOfEven(List<Integer> integerList) 
{
    int sum = 0;
    for (Integer i: integerList) {
    	if (i % 2 == 0)
            sum += i;			//Integer to int
    }
    return sum;
}

In above example, the remainder (%) and unary plus (+=) operators does not apply on Integer objects. The compiler automatically converts an Integer to an int at runtime by invoking the intValue() method.

Autoboxing and unboxing lets developers write cleaner code, make it easier to read.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket
Comments are closed on this article!

Search Tutorials

Java Basics

  • Java Introduction
  • Java Installation
  • Java Hello World
  • Java JDK, JRE and JVM
  • Java Classes and Objects
  • Java ClassPath
  • Java Operators
  • Java Data Types
  • Java Primitive Types
  • Java Variables
  • Java Comments
  • Java main() Method
  • Java Command Line Args
  • Java Wrapper Classes
  • Java Types of Statements
  • Java Block Statement
  • Java Pass-by-Value
  • Java System Properties
  • Java Static Import
  • Java hashCode() and equals()
  • Java Immutable Class
  • Java 32-bit vs 64-bit
  • Java java.exe vs javaw.exe
  • Java Generate Bytecode
  • Java Naming Conventions
  • Java Little-Endian vs Big-Endian

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces