Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconWhat is Autoboxing in Java? With Examples

What is Autoboxing in Java? With Examples

Last updated:
4th Jun, 2023
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
What is Autoboxing in Java? With Examples

In the contemporary world, Java is the renowned choice for scripting Android applications. It also finds extensive demand in the machine learning environment, cloud applications and IOT technology. The developers need to have a thorough understanding of the recent trends in Java programming. A lucrative professional prospect is assured for Java developers because the language has a firm presence in the enterprise. Java is not only a leading object-oriented language in the android mobile application market but also in the field of backend market. 

Basics of autoboxing in Java:

While scripting a program, primitive data types are used in most of the programming languages. However, in object-oriented programming languages such as Java, the primitive data types are not effective in some scenarios and they fall short in the realm. To overcome the limitations of the primitive data types, wrappers are used. This phenomenon is called autoboxing. Let us discuss more about autoboxing in Java in the subsequent sections. 

Check out our free technology courses to get an edge over the competition.

Autoboxing and Autounboxing:

Autoboxing is the process of conversion of a primitive value into a wrapper class’s object. For example, an int data type is converted to an integer class. The autoboxing function is performed by a Java compiler if the primitive value is:

Ads of upGrad blog
  • Assigned to a variable of respective wrapper class.
  • Passed as an argument to a method that uses an object of the respective wrapper class.

Autoboxing is a reverse of the autoboxing function. The conversion of a wrapper type object to its respective primitive value is referred to as unboxing. Let us consider an example of an Integer object converted into an int data type. The Java compiler performs unboxing when a wrapper class object is:

  • Assigned a variable of the respective primitive type.
  • Passed as an argument to a method that requires the corresponding primitive type’s value.

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Autoboxing and Unboxing in Java: Examples

Let’s begin with an autoboxing in Java example:

int ‘i’ = 10;

Integer ‘j’ = i; // autoboxing

In the above example, we’re assigning the value of the primitive integer variable’  i’ to its corresponding wrapper class object ‘j’ using autoboxing. 

Consider the following example of unboxing in Java:

Integer ‘i’ = 10;

int ‘j’ = ‘i’; // unboxing

In this example, we’re assigning the value of the wrapper class object ‘i’ to the primitive integer variable’ j’ using unboxing.

Autoboxing in Detail:

The terms boxing and autoboxing are alternately used in many cases to describe the same concept. However, there is a subtle difference between the two terms. The term ‘boxing’ refers to wrapping of a primitive data type to form an object. Let us consider an example to understand this concept. Consider the Java code statement written below. 

int FirstNumber = 1;

In this statement, the variable ‘FirstNumber’ is of int data type which is primitive. It can be converted to an object using the statement below. 

Integer SecondNumber = new Integer(2);

The variable SecondNumber in the above statement is not of the primitive int data type. Instead, it is an Integer object. This process of conversion of primitive types of data into an object is referred to as boxing. The easiest way of performing this task is by developing a class that contains a single attribute of int data type. A constructor of int type value is assigned to the class attribute. Several methods are used to manipulate the int value. The wrapper classes in Java can be used to enable the conversion of other data types into an object. 

Autoboxing is the function performed automatically by the compiler without mentioning it explicitly.   

MyList.add(Integer.valueOf(i));

This is the line added by the compiler into our program.

In the above code statement, the name of the class ‘Integer’ is specified before mentioning the method valueOf() because valueOf() is a static method. 

What is unboxing in Java?

Now that we have understood the process of conversion of primitive data types into objects, let us look into the process that does the reverse function of boxing. Unboxing, as mentioned earlier, refers to the process of conversion of an object of wrapper class type into its primitive data types.

When the process of unboxing is performed automatically by the compiler without mentioning it explicitly in the program, it is referred to as Auto unboxing. Let us consider the example shown below to understand the auto unboxing. 

Performance Impact of Autoboxing in Java

While autoboxing and unboxing are convenient features in Java, they can impact performance, especially when used in large collections such as arrays or lists. This is because autoboxing and unboxing contain developing and manipulating wrapper objects, which may be inefficient compared to running with primitive types without delay. As a general rule, avoiding autoboxing and unboxing in performance-vital sections of code is recommended and, as a substitute, using primitive sorts on every viable occasion.

Rules for Autoboxing in Java

There are positive regulations to remember when working with autoboxing in Java. For instance, now, not all primitive types may be autoboxed. Only the primitive types may be autoboxed: ‘boolean’, ‘byte’, ‘char’, ‘quick’, ‘int’, ‘long’, ‘flow’, and ‘double’. 

Additionally, whilst autoboxing a value, Java will most effectively create a brand new object if the fee is outdoor and the wrapper class can represent the variety of values. For instance, autoboxing the cost ’10’ to an ‘Integer’ item will not create a new object because ’10’ is in the range of values that can be represented by means of ‘Integer’.

Examples of When Autoboxing Can Lead to Unexpected Results

While autoboxing can be handy, it can also lead to surprising consequences in some instances.

For instance, recall the code given below:

Integer ‘i’ = 10;

Integer ‘j’ = 10;

System.out.println’(i == j)’;

In this example, we’d assume the output to be actual because each ‘i’ and ‘j’ have the identical value of ’10’. However, the output will be fake because’ i’ and ‘j’ are unique items, and the ‘= =’ operator compares object references, not values. To avoid this difficulty, we can use the ‘equals()’ approach to compare the values of ‘i’ and ‘j’.

More about Wrapper Classes:

Ads of upGrad blog

In the example for autoboxing, the variable I is of int data type and the object Integer is a wrapper class. The wrapper class in Java is available for all the primitive data types. These classes enable the user in the conversion of a variable from primitive data type to the corresponding object of wrapper class type. The wrapper class methods are used in the manipulation of the values. The primitive data types and their respective wrapper classes are summarized in the table below. Note that the name of the wrapper classes begin with an uppercase letter. 

Primitive data type

Corresponding wrapper class

byteByte
booleanBoolean
charCharacter
int Integer
floatFloat
ShortShort
LongLong
doubleDouble

Merits of Autoboxing and auto unboxing in Java:

  • The process of autoboxing and unboxing enables the programmers to script a well-structured and easily readable code.
  • The process also enables the users to switch between the primitive data types and the objects of the wrapper class alternately. Hence, the explicit typecasting is not required.

Additional Features Related to Autoboxing and Unboxing

Java has various supplementary autoboxing and unboxing features, such as the ability to convert between primitive types and their related wrapper classes utilising wrapper classes and methods. For example, the ‘Integer.parseInt()’ function has been used to convert an integer string representation to its corresponding primitive integer type; an ‘Integer.valueOf()’ method can be used to turn a primitive integer into its corresponding wrapper object. Besides that, Java includes wrapper classes comprising ‘Double,’ ‘Boolean,’ and ‘Character’ for additional base types that may be used similarly to Integer.

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Programme in Software Development – Specialisation in Full Stack Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1What makes autoboxing different from unboxing in Java?

Autoboxing is converting a primitive type to its corresponding wrapper class. At the same time, unboxing is the other system of converting a wrapper elegance object to its corresponding primitive type.

2When shall I keep away from the use of autoboxing in Java?

Autoboxing can affect overall performance, particularly in big collections with arrays or lists. As a preferred rule, avoiding autoboxing and unboxing in overall performance-vital sections of code is recommended, and alternatively, using primitive types on every occasion is viable.

Explore Free Courses

Suggested Blogs

Scrum Master Salary in India: For Freshers & Experienced [2023]
900134
Wondering what is the range of Scrum Master salary in India? Have you ever watched a game of rugby? Whether your answer is a yes or a no, you might h
Read More

by Rohan Vats

05 Mar 2024

SDE Developer Salary in India: For Freshers & Experienced [2024]
904669
A Software Development Engineer (SDE) is responsible for creating cross-platform applications and software systems, applying the principles of compute
Read More

by Rohan Vats

05 Mar 2024

System Calls in OS: Different types explained
5011
Ever wondered how your computer knows to save a file or display a webpage when you click a button? All thanks to system calls – the secret messengers
Read More

by Prateek Singh

29 Feb 2024

Marquee Tag & Attributes in HTML: Features, Uses, Examples
5058
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More

by venkatesh Rajanala

29 Feb 2024

What is Coding? Uses of Coding for Software Engineer in 2024
5030
Introduction  The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More

by Harish K

29 Feb 2024

Functions of Operating System: Features, Uses, Types
5063
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More

by Geetika Mathur

29 Feb 2024

What is Information Technology? Definition and Examples
5026
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More

by spandita hati

29 Feb 2024

50 Networking Interview Questions & Answers (Freshers & Experienced)
5074
In the vast landscape of technology, computer networks serve as the vital infrastructure that underpins modern connectivity.  Understanding the core p
Read More

by Harish K

29 Feb 2024

10 Best Software Engineering Colleges (India and Global) 2024
5381
Software Engineering is developing, designing, examining, and preserving software. It is a structured and trained approach through which you can devel
Read More

by venkatesh Rajanala

28 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon