Java app developers, protect your intellectual property and improve the end-user experience. Get Excelsior JET.

An Unorthodox “Solution” to an NPE Puzzle

I’ve been subscribed to Java Performance Tuning by Jack Shirazi and Kirk Pepperdine forever (compared to other e-newsletters), not least because of the introductory pieces. Jack opened the Feb 2014 issue with a small puzzle stemming from a real problem his colleague encountered. I forwarded it to our developers immediately:

This month I’ve got a little puzzle for you. How can you get a null pointer exception from the following piece of code?

    //map is an instance of HashMap
    x = map.get("hello");

To be clear, “map” is not null, it is an instance of the standard HashMap class from the JDK, the get() method and all the other HashMap methods are the normal ones you have in the JDK, and there has been no bytecode injection. Oh, and the process is not out of memory, hasn’t been out of memory, and the HashMap instance has not been used in more than one thread.

If you cannot figure out the answer, take a peek at issue #159 of the newsletter. One of my colleagues, however, have come up with a deliberately coded “solution” to the problem:

import java.util.HashMap;

public class ShootMyselfInTheFoot {
    private static class Damn {
        // Load
        public int hashCode() {
            return "hello".hashCode();

        // Aim
        public boolean equals(Object obj) {
            obj = obj != null ? null : "";
            return obj.equals(obj);

    public static void main(String[] args) {
        // Fire!
        HashMap map = new HashMap();
        map.put("hello", null);
        map.put(new Damn(), null);

        Object x = map.get("hello");

Left me wondering if might make sense for an advanced obfuscator or copy protection tool inject pieces of such meaningful-looking yet unexpectedly failing code into the application, of course making sure that it never receives control (except if license check has failed a few million CPU cycles before.)

Categories: Java

Tags: ,

Comments are closed.