|
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
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.
|
|
Message #215844
Post reply
Post reply
Post reply
Go to top
Go to top
Go to top
|
 |
Re: Autoboxing and NPE
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
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
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
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
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
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 |
 |
 |
|
|
Featured BlogsFeatured BlogsFeatured Blogs |
 |
 |
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.
|
Brian McCallister looks at the Lucene search engine and shows us how to index and retrieve objects from a sample Student application.
|
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.
|
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.
|
Brian McCallister has been playing with JDO 2 fetch groups, ZODB, thinking about TranQL, playing with Prevayler, and looking at TORPEDO.
|
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.
|
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.
|
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
|
|
|