About Lukas Eder

Lukas is a Java and SQL enthusiast developer. He created the Data Geekery GmbH. He is the creator of jOOQ, a comprehensive SQL library for Java, and he is blogging mostly about these three topics: Java, SQL and jOOQ.

Java Auto-Unboxing Gotcha. Beware!

What do you think that the following code snippet will print?
 
 
 
 
 
 
 
 
 
 

Object o = true ? new Integer(1) : new Double(2.0);
System.out.println(o);

Yes! It will print:

1.0

What? 1.0? But I have assigned an Integer to my o variable. Why does it print 1.0? It turns out that there is a subtle little specification section in the JLS’s §15.25, which specifies the ternary operator. Here’s what is applied to the above:

The type of a conditional expression is determined as follows:

  • [...]
  • Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:
    • [...]
    • Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.
      Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).

Binary numeric promotion may implicitly perform unboxing conversion! Eek! Who would have expected this? You can get a NullPointerException from auto-unboxing, if one of the operands is null, the following will fail

Integer i = new Integer(1);
if (i.equals(1))
    i = null;
Double d = new Double(2.0);
Object o = true ? i : d; // NullPointerException!
System.out.println(o);

Obviously (obviously !?) you can circumvent this problem by casting numeric types to non-numeric types, e.g. Object

Object o1 = true 
  ? (Object) new Integer(1) 
  : new Double(2.0);
System.out.println(o1);

The above will now print

1

Credits for discovery of this gotcha go to Paul Miner, who has explained this more in detail here on reddit.
 

Reference: Java Auto-Unboxing Gotcha. Beware! from our JCG partner Lukas Eder at the JAVA, SQL, AND JOOQ blog.
Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

4 Responses to "Java Auto-Unboxing Gotcha. Beware!"

  1. lasne says:

    in fact the point there is more about the ternary operator that is a bit weird in some cases
    http://selectedjavalinks.blogspot.fr/2013/09/if-else-bit-weird-but-let-me-explain.html

    notice that the some code especially the last sample might not gives the same result using groovy and using java

    • Yannick Majoros says:

      Right, nothing to do with unboxing. This will print the same result without any unboxing:

      System.out.println(true ? 1 : 2.0);

      Recommanding to cast to Object is a bad idea.

      So is this in a post-java 1.4 world:

      Integer i = new Integer(1);

      Should simply be:

      Integer i = 1;

  2. Witek Baranowski says:

    It’s not new and for sure Paul Miner didnt discover it :)

    Link to Polish java beginner tutorial from 2010…

    http://javastart.pl/efektywne-programowanie/javatraps-002/

Leave a Reply


7 + = sixteen



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books