DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Thermometer Continuation in Scala
  • Thumbnail Generator Microservice for PDF in Spring Boot
  • From Zero to Meme Hero: How I Built an AI-Powered Meme Generator in React

Trending

  • Java Virtual Threads and Scaling
  • Debugging Core Dump Files on Linux - A Detailed Guide
  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  • Recurrent Workflows With Cloud Native Dapr Jobs
  1. DZone
  2. Data Engineering
  3. Data
  4. Autoboxing and Its Pitfalls

Autoboxing and Its Pitfalls

Learn all about the Autoboxing feature of the Java, including what it is, why it's needed, pros and cons.

By 
T Tak user avatar
T Tak
·
Mar. 22, 16 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
25.0K Views

Join the DZone community and get the full member experience.

Join For Free

Autoboxing

What is Autoboxing?

Autoboxing is a feature of the Java language introduced in Java 1.5. When a Java compiler makes an automatic conversion between the primitive types and their corresponding object wrapper class, it is called autoboxing. The process of creating a Wrapper class like Float from a primitive type like float is called boxing. And the process of creating a primitive type like int from Wrapper class like Integer is called unboxing.

 Why Do We Need Autoboxing?

A primitive type cannot be put into a collection as collections can only hold object references. So as to put a primitive type to collections a programmer would have to always box a primitive type and put into collections. And then on retrieval of the value, he/she would have to unbox it. This would be a pain and was so until java 1.4. The autoboxing and unboxing automates this and hence makes the code easier to read and less painful for developers to write.

Pitfalls of Autoboxing

Performance

Autoboxing does create objects which are not clearly visible in the code. So when autoboxing occurs performance suffers. If you see the Javadocs:

It is not appropriate to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code. An Integer is not a substitute for an int; autoboxing and unboxing blur the distinction between primitive types and reference types, but they do not eliminate it.

Unexpected Behavior

Confused Equals

Autoboxing has brought with itself a lot of things that just are not obvious to a programmer. What would be the output of below code?

Long longWrapperVariable=2L ;
System.out.println(longWrapperVariable.equals(2));
System.out.println(longWrapperVariable.equals(2L));

Here is what the above code prints:

false
true

If you are wondering what happened above, 2 was boxed to Integer and henceequals could not compare it with Long. And 2L was boxed to Long and hence returned true.

Caching of Primitive by Wrapper Classes

And on top of that, if you add the below Java Language Specification, you would just be adding more confusion

 If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Here is simple example that demonstrates the caching of int:

System.out.println(Integer.valueOf("127")==Integer.valueOf("127"));
System.out.println(Integer.valueOf("128")==Integer.valueOf("128"));

What would be the result of above code?

true
false

This works on a JVM that is only caching int between -128 to 127.

Ambiguous Method Calls

What would be the result of below code?

public static void main(String[] args) throws Exception {
int test = 20;
myOverloadedFunction(test);
}

static void myOverloadedFunction(long parameter) {
System.out.println("I am primitive long");
}

static void myOverloadedFunction(Integer parameter) {
System.out.println("i am wrapper class Integer");
}

And the output is:

I am primitive long

The answer is that the compiler will choose widening over boxing, so the output will be “I am primitive long.”

OutOfMemoryError

A boxing conversion may result in an OutOfMemoryError if a new instance of one of the wrapper classes (Boolean, Byte, Character, Short, Integer, Long, Float, or Double) needs to be allocated and insufficient storage is available.

NullPointerException

  While running the below code, NullPointerException(NPE) can be thrown and it is not quite obvious from the code if you are not aware of autoboxing. Eclipse will show the warning for this code, “Null pointer access: This expression of type Boolean is null but requires auto-unboxing.” Because I made it obvious to eclipse that testNPEvariable is null.

Boolean testNPE = null;   
if(testNPE){
 System.out.println("will never reach here");
}

Let me make it less obvious to the eclipse in the below code. And the warning will be gone but the possibility of NullPointerException still exists, as we are not handling the case of Boolean variable being 

private void testAutoUnboxingNPE(Boolean testNPE) {
 if(testNPE){
  System.out.println("I am true");
 } else if(testNPE){
  System.out.println("I am false");
 }
}

How to avoid this NullPointerException in Boolean unboxing: Here is the ugly code to avoid the exception. Here we handle it in a way that accepts that Boolean has 3 possible values, null, true or false.

private void testAutoUnboxingNPE(Boolean testNPE) {
 if(Boolean.TRUE.equals(testNPE)){
  System.out.println("I am true");
 } else if(Boolean.FALSE.equals(testNPE)){
  System.out.println("I am false");
 } else{
  System.out.println("I am null");
 }
}

So from the above code, it is obvious that you have defined the behavior of the above method in case Boolean object is null. I usually document the behavior of the method for all three case in the Javadocs.

Data Types

Published at DZone with permission of T Tak. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Thermometer Continuation in Scala
  • Thumbnail Generator Microservice for PDF in Spring Boot
  • From Zero to Meme Hero: How I Built an AI-Powered Meme Generator in React

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!