Friday, 27 May 2016

Java null and NullPointerException

NullPointerException: An attempt was made to use a null reference in a case where an object reference was required.
NullPointerException is more famous to Java programmers, than fashion to Paris. When you start breaking the beurette and Pipette in Java lab, first thing you will get is NullPointerException. In this tutorial lets discuss about, do we need NullPointerExceptions and why does it comes and how to solve a NullPointerException (NPE). Also we need to study about null, which causes the NullPointerException.
Before going into detail, is NullPointerException named correctly? i think it should have beed name as NullReferenceException as correctly done in dotNet. Hey, I heard there are no pointers in Java atleast for namesake! then how come it is NullPointerException. You might appreciate this after reading the complete story.

Why did NullPointerException became so famous?

Error description for NullPointerException doesn’t tells the name of the null variable, which caused the exception. The programmer, mostly beginner spends lot of time to figure out where the error is. Also it happens so frequently that you get annoyed. Error reported just says the line number at which it occurred. NullPointerException is a RuntimeException.
In a code block, if there is a possibility of null pointer exception it should be checked and reported at compile time. Yes there is language ‘Nice’ which does it and there is no chance of getting a NullPointerException.

Scenarios when we get NullPointerException:

Java API documentation says that NullPointerException can be thrown, when there is an attempt to use null where an object is required. That is you are trying to access a reference where there is no value. Main scenarios are when, calling the instance method of a null object and accessing or modifying the field of a null object. When you pass null to a method when it expects a real value. It means to say that null object is used illegally.
So how do we get a null object in place? When you create an object and not initializing it. When you access a method and it returns a null object.

How to solve a NullPointerException in Java?

It is simple, put a null check! Surround your object with if statement like
Object mayBeNullObj = getTheObjectItMayReturnNull();
if (mayBeNullObj != null) { // to avoid NullPointerException
mayBeNullObj.workOnIt();
}

If you think it is so easy and the subject is done, then you are caught wrong. I think the above method is ugly! Imagine a situation where you work using many third party components (methods), how many if conditions will you put to solve one NullPointerException? It will pollute the code. When you deal with third party components and it is supplied with poor javadoc (it always happens!), there is no other option available but to use this ugly way. If not, you can avoid this by using a better design of software. A simple example is to have proper ‘required field’ check at GUI level, when your business logic expects an operation on a given object. Then you can depend on your design and omit the if-null-check which beefs up your code.
There is a default value for all primitives in Java and it is initialized with it. Why not have something like that for objects? So that null will never exist and the whole world’s NullPointerException problem is solved. Why do we have null in Java? We need it to use in places where there is absense of information. We are depicting real world information in Java programming using OOPS. Zero is absense of information, can I use zero as a replacement for null. No! In mathematics itself zero can be used when there is absense of information, only when you are dealing with numbers. For example when you are working in real algebra, you have a null set not number zero. Of course the size of that is zero ;-) So in real world 0 and absense of existense are not same. Therefore one cannot use empty Sting “” or zero in place of null in java.
Too much techie information for the academics, you may omit this paragraph without loosing integrity of information.
Java Virtual Machine (JVM) specification gives 24 operations that throws NullPointerException. They are aaload, aastore, arraylength, athrow, baload, bastore, caload, castore, daload, dastore, faload, fastore, getfield, iaload, iastore, invokeinterface, invokespecial, laload, lastore, monitorenter, monitorexit, putfield, saload, sastore. Of those 21 would be supplemented by versions that would not throw NullPointerException. The 3 that wouldn’t be supplemented are athrow, monitorenter and monitorexit. 16 of the 21 involve loading or storing the primitive types from or in arrays; 2 involve the same with object references; 2 more: getfield & putfield; 2 for method invocation; and 1 for the length of the array.

Guidelines to solve or deal with NullPointerException:

  • Prune null at design level, and don’t allow the possibilty of having null value in object where the business scenario doesn’t allows.
  • Always declare variables just before where they are going to be used.
  • Always use if-null-check when you don’t have control over the object’s value. (Ugly but no choice!)
    Put the string constant first from left when comparing values with a String variable.
  • Religiously initialize (fill) arrays immediately after declaration. Arrays mostly causes NullPointerException.
  • Return Iterators instead of Lists. This allows to return empty Iterator and the consumer need not do if-null-check. NullPointerException will not creep into this pattern.
  • Erroneously don’t declare a variable inside a constructor, it will hide the instance variable.


SOURCE

No comments:

Post a Comment