Exception in java

NullPointerException is an Exception which Java can throw at runtime. Its name is confusing because it is not possible to create pointers explicitly in Java! But it has been around since the very start of the Java language, and wisely, the Java designers never change anything that would break existing code, so the confusing name remains.

When you create a variable in Java that can hold any kind of object, that variable is a reference. You can think of it like a pointer to a memory location, except that you can’t access the real pointer, only a reference to it.

In Java, all object references can hold either a pointer to one instance of an object, or the special value null, which means no object. That’s part of the definition of the Java language.

If you try to access an object in a variable at runtime, and at that time it is a reference to null, then Java will throw a NullPointerException to tell you that the object you were expecting has not been assigned to your variable.

It’s very common to see checks for null in Java code, to avoid this exception being thrown. Some other languages have special types of expression that only proceed if none of the object references are null, but Java doesn’t, which I think is a pity.