Another "Gotcha", this time in HTML

I couldn't resist another dorky software engineering post. Non dorks may stop reading here.

At work the other day, while debugging my code, I noticed that one of my servlets was getting called twice for each page load. What was even more mysterious was that the second call would happen as the page was partially loaded. I scoured my code for iframes, accidental use of the servlet, rouge AJAX calls and so on, but couldn't find a thing. I resorted to just commenting out huge chunks of the page at a time to see which parts were causing the second page load. After a while, I narrowed it down to this:

<img src="$imgUrl" />

where $imgUrl is a variable who's value is filled in at runtime. So, you might be wondering how the heck an img tag can cause the entire page to reload? Well, it turns out (at least in Firefox 3) that if you have an img tag with a blank src attribute, the browsers tries to load an image at your base URL - that is, the URL of the page you're on. Therefore, every time $imgUrl turned out to be blank, my browser would re-request the page I was on. This, of course, caused a bad performance hit, was screwing up statistics and so on.

Moral of the story: make sure that your img tags never have an empty src attribute.

A Subtle Java 1.5 "Gotcha"

I couldn't resist creating this very short, dorky and entirely programming-focused entry today. If you are not a software engineer, read no further. You have been warned.

I recently ran across a subtle way a handy Java 1.5 feature can sneak up and cause issues. Perhaps if I had spent more time pouring over the specs & documentation, it would've been very obvious, but alas, it definitely caught me by surprise. The problem was a null Pointer Exception (NPE) which I tracked down to the following line of code:

int id = map.get(key)

The obvious culprit was that HashMap named map was null, but as I stepped through the code, I found to my surprise that it wasn't. Neither was key, for that matter. So how the hell was I getting an NPE? Take a look at the declaration of map:

Map<String,Integer> map = new HashMap<String,Integer>();

Note how the values in map are Integer objects, but I'm setting the result of the get call to a primitive int. In Java 1.5, this is allowed as Java will automatically unbox the Integer into an int. But what happens if the value returned by get is null? Well, the auto unboxing can't convert that to any int value - returning some default value like 0 or -1 would be very deceiving - so you get a big old NPE.

Moral of the story: auto boxing and unboxing are very handy features to keep your code clean and readable, but keep NPE's in mind every time you use them.