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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Why Round-Robin Won't Save You: Load Balancing Challenges in Data Streaming Services With Heterogeneous Traffic
  • Ingesting Fixed-Width Mainframe Files Into Delta Lake: The Details Nobody Writes Down
  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables
  • The Hidden Cost of Overprivileged Tokens: Designing Messaging Platforms That Assume Compromise

Trending

  • Your AI Agent Tests Are Passing, But Your Agent Is Still Broken
  • Feature Flag Debt: Performance Impact in Enterprise Applications
  • Beyond Manual Annotation: Engineering Self-Correcting Pseudo-Labeling Pipelines
  • Build a GitHub Slack Bot With AWS Bedrock and MCP, Part 2
  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.8K 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

  • Why Round-Robin Won't Save You: Load Balancing Challenges in Data Streaming Services With Heterogeneous Traffic
  • Ingesting Fixed-Width Mainframe Files Into Delta Lake: The Details Nobody Writes Down
  • Beyond Partitioning and Z-Order: A Deep Dive into Liquid Clustering for Unity Catalog Managed Tables
  • The Hidden Cost of Overprivileged Tokens: Designing Messaging Platforms That Assume Compromise

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook