667481 members! Sign up to stay informed.

Sponsored Links


Resources

Enterprise Java
Research Library

Get Java white papers, product information, case studies and webcasts

Blogs Blogs Blogs Messages: 8 Messages: 8 Messages: 8 Printer friendly Printer friendly Printer friendly Post reply Post reply Post reply XML XML XML

Autoboxing and NPE

Posted by: Kirk Pepperdine on August 11, 2006 DIGG
If you are new to Java 5 and have been running into mysterious null pointer exceptions, then you may find Burt Beckwith's blog enlightening. In the entry Burt explains what he did to locate and eliminate a mysterious null pointer exception

Burt was relying on autoboxing to allow him to use the primitive type int as keys in a map when he made this discovery.

I spent a while earlier today debugging a very small block of code that was throwing a NPE. There were few options for instances that could be null, but since I was looking in the wrong place for the problem, it took longer than it should have to fix

Autoboxing has been designed to address the inability to mix objects and primitives in the Java language. What Burt was trying to do was store primitive values in a Map. Since both the key and value pairs must be objects, primitives must be wrapped before you can save them. Prior to Java 5, this meant doing something map.put( new Integer( integerKey), value). With Java 5 auto-boxing comes to the rescue so that we can now do; map.put( integerKey, value). The magic is the compiler will add in all the stuff needed to create the wrapper.

Under the hood when you autobox and treat an Integer as an int or vice versa, the compiler inserts a call to intValue()

The difficulties comes when you need to map back to an integer. You may have a 0 or you may have a null. However since 0 is meant to represent both the designers had to make a choice and they choose null. The inject code to support auto-boxing looks something like this;


Integer z = Integer.valueOf(5);
Integer i = null;
int j = i.intValue();

The result can be a hidden NPE.

Threaded replies

·  Autoboxing and NPE by Kirk Pepperdine on Fri Aug 11 06:12:11 EDT 2006
  ·  I warned and blogged about this back in march 2004 by Geert Bevin on Fri Aug 11 13:43:34 EDT 2006
    ·  Generics = Good, Boxing = bad... by Michael Tholkes on Tue Aug 15 12:43:42 EDT 2006
  ·  Re: Autoboxing and NPE by Ian Hlavats on Tue Aug 15 20:58:35 EDT 2006
    ·  Re: Autoboxing and NPE by Bogdan Mocanu on Wed Aug 16 01:22:06 EDT 2006
      ·  Re: Autoboxing and NPE by Ian Hlavats on Thu Aug 17 19:38:15 EDT 2006
        ·  Exceptions are usually good by Sharique Abdullah on Wed Sep 06 01:10:56 EDT 2006
  ·  Re: Autoboxing and NPE by Dave Lorde on Wed Sep 06 04:54:02 EDT 2006
    ·  Re: Autoboxing and NPE by Keith Moore on Wed Nov 22 09:29:17 EST 2006
  Message #215529 Post reply Post reply Post reply Go to top Go to top Go to top

I warned and blogged about this back in march 2004

Posted by: Geert Bevin on August 11, 2006 in response to Message #215466
http://rifers.org/blogs/gbevin/2004/3/11/the_dangers_of_auto_unboxing

  Message #215788 Post reply Post reply Post reply Go to top Go to top Go to top

Generics = Good, Boxing = bad...

Posted by: Michael Tholkes on August 15, 2006 in response to Message #215529
This is why I've used generics instead of boxing...

  Message #215844 Post reply Post reply Post reply Go to top Go to top Go to top

Re: Autoboxing and NPE

Posted by: Ian Hlavats on August 15, 2006 in response to Message #215466
I like the idea of autoboxing, but I think the implementation in Java 5 leaves something to be desired.

For instance, why doesn't the following code do what it seems like it should do?

Boolean enabled;
if (enabled) {
System.out.println("Enabled!");
}


If you run this code, you will get a NullPointerException because the Boolean property is null and autoboxing attempts to convert null to a primitive boolean.

Why doesn't it just convert it to false? Similarly, why doesn't a null Integer reference simply get converted to 0 (zero)? And a null Double reference to 0d (zero double)? And a null Float reference to 0f (zero float)? And so on...

This leads to some awkward code:

if (enabled != null && enabled) {
System.out.println("Enabled!");
}


What can you do.

  Message #215858 Post reply Post reply Post reply Go to top Go to top Go to top

Re: Autoboxing and NPE

Posted by: Bogdan Mocanu on August 16, 2006 in response to Message #215844
Ian,

I must say I don't agree with you. It is natural to get a NPE there, since you are using a variable of a non-primitive type, which is null. You cannot expect Java to make asumptions about what the value of that variable should be. If it is null, any use of that variable, in other contexts than a comparison to another variable, is supposed to throw NPE.

Secondly, I also don't agree with the Kirk's blog message. Since you are using a map, you must be aware of the fact that when you are retriving an element by a certain key, you could get a NPE, if that key doesn't exist. So the natural way of using the map should be: check first for the non-null return and then try to convert the returned value directly to a primitive type. Otherwise you get NPE, which is normal, in my opinion.

  Message #216006 Post reply Post reply Post reply Go to top Go to top Go to top

Re: Autoboxing and NPE

Posted by: Ian Hlavats on August 17, 2006 in response to Message #215858
Ian,

I must say I don't agree with you. It is natural to get a NPE there, since you are using a variable of a non-primitive type, which is null. You cannot expect Java to make asumptions about what the value of that variable should be. If it is null, any use of that variable, in other contexts than a comparison to another variable, is supposed to throw NPE.

Hi Bogdan,

You are right, and your reply is very close to the text in the Sun documentation on autoboxing:

The result of all this magic is that you can largely ignore the distinction between int and Integer, with a few caveats. An Integer expression can have a null value. If your program tries to autounbox null, it will throw a NullPointerException.
(Sun Java Website - Autoboxing)

In the spirit of comparative programming philosophy, I have a Perl background, and I guess I have become used to Perl's generous interpretation of source code. It has even been described as a "DWIM" (Do What I Mean) programming language:

As much as possible, features should do what the user expects. This concept of DWIM, or "Do What I Mean," is largely a matter of intuition. The user's experiences, language exposure, and cultural background all influence their expectations. This means that intuition varies from person to person. An English speaker won't expect the same things as a Dutch speaker, and an Ada programmer won't expect the same things as a COBOL programmer.

The trick in design is to use the programmer's intuitions instead of fighting against them. A clearly defined set of rules will never match the power of a feature that "just seems right."
(Perl.com - Design Philosophy)

Food for thought.

Ian

--
Ian Hlavats
Tarantula Consulting Inc.
http://www.tarantulaconsulting.com

  Message #217375 Post reply Post reply Post reply Go to top Go to top Go to top

Exceptions are usually good

Posted by: Sharique Abdullah on September 06, 2006 in response to Message #216006
Being a developer, I think exceptions are annoying when hard to find out
BUT they are better to be thrown instead of some automatic conversion ... like interpreting a null value as 0 or false or something like that... One of the best things about java is its type safety while automatically converting values from and to null (and etc) hurts the type safety very badly... and trust me solving a bug with a non type safe language is very much more troublesome as in a typesafe language... so I think we should not want things which eventually will hurt ourselves...
and I think that NPE are not hidden by any means I think, its just that you check only for those things which you usually practise ... instead of everything ... :)

  Message #217388 Post reply Post reply Post reply Go to top Go to top Go to top

Re: Autoboxing and NPE

Posted by: Dave Lorde on September 06, 2006 in response to Message #215466
I guess if you want to be safe with autoboxed primitives in containers, and you don't like checking for nulls, you should use a container that doesn't permit null values... Hashtable is one such, although it has synchronisation overheads - perhaps there should be others? I suppose you could write your own wrapper classes, but autoboxing was supposed to avoid all that...

  Message #222721 Post reply Post reply Post reply Go to top Go to top Go to top

Re: Autoboxing and NPE

Posted by: Keith Moore on November 22, 2006 in response to Message #217388
I guess if you want to be safe with autoboxed primitives in containers, and you don't like checking for nulls, you should use a container that doesn't permit null values... Hashtable is one such, although it has synchronisation overheads - perhaps there should be others? I suppose you could write your own wrapper classes, but autoboxing was supposed to avoid all that...


You could use HashMap instead of a HashTable. HashMap is NOT syncronized. So if you dont need syncronization then HashMap works great.

Featured SectionFeatured SectionFeatured Section
Weekly Blogs UpdateWeekly Blogs UpdateWeekly Blogs Update
Stay current on the most informative blogs in the enterprise Java community. Join TheServerSide.com and sign up for the Blogs Update. Let TheServerSide.com do the work for you -- we scan thousands of blogs to find the ones most worthy of your attention.
Featured BlogsFeatured BlogsFeatured Blogs

Optimizing CMP Performance in Weblogic with Long-term Caching

Dmitri Maximovich has written a blog on optimizing CMP EJB performance in WebLogic, by addressing optimistic concurrency, along with some of the implications of doing so.

Using Lucene with OJB

Brian McCallister looks at the Lucene search engine and shows us how to index and retrieve objects from a sample Student application.

JDK 5 in Practice

Cedric Beust has been in a position to actually code with JDK 5 for over six months. He has written up his thoughts on the new features, and how he has found them to be in practice.

Dear Manager, They Need a Build Machine

Mike Clark has started a series of entries of letters that you wish you could write to your boss. It consists of concepts which seem so obvious to us, but which the bosses don't get.

Are we doing OR mapping wrong?

Brian McCallister has been playing with JDO 2 fetch groups, ZODB, thinking about TranQL, playing with Prevayler, and looking at TORPEDO.

Fear and Testing

Frank talks about fear and how it can derail efforts to find and solve scalability and performance problems. He has seen a lot of fear on his various engagements, and here he talks about why, and how.

Components, Design, and Functions

Brian McCallister has kindly rambled on about IoC, and design in web applications. He discusses what has worked well for him (and others) in the last year.

JDK 1.5 from Joshua and Neal

Matt Raible went to the Denver JUG meeting with Neal Gafter, and Joshua Bloch. They discussed the new features of Java 5, and Matt details the features, and when to use them.
Featured Blogs Archive

News | Blogs | Discussions | Tech talks | Patterns | Reviews | White Papers | Downloads | Articles | Media kit | About
Java Solutions
All Content Copyright ©2007 TheServerSide Privacy Policy
Site Map