Null pointers are one of the most common errors that Java programmers make. Compilers can’t check this one for you – it will only surface at runtime, and if you don’t discover it, your users certainly will.
When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown. The cause of null pointers can be varied, but generally it means that either you haven’t initialized an object, or you haven’t checked the return value of a function.
Many functions return null to indicate an error condition – but unless you check your return values, you’ll never know what’s happening. Since the cause is an error condition, normal testing may not pick it up – which means that your users will end up discovering the problem for you. If the API function indicates that null may be returned, be sure to check this before using the object reference!
Another cause is where your initialization has been sloppy, or where it is conditional. For example, examine the following code, and see if you can spot the problem.
public static void main(String args[])
{
// Accept up to 3 parameters
String[] list = new String[3];
int index = 0;
while ( (index < args.length) && ( index < 3 ) ) {
list[index++] = args[index];
}
// Check all the parameters
for (int i = 0; i < list.length; i++){
if (list[i].equals "-help"){
// .........
}else
if (list[i].equals "-cp"){
// .........
}
// else .....
}
}
This code (while a contrived example), shows a common mistake. Under some circumstances, where the user enters three or more parameters, the code will run fine. If no parameters are entered, you’ll get a NullPointerException at runtime. Sometimes your variables (the array of strings) will be initialized, and other times they won’t. One easy solution is to check BEFORE you attempt to access a variable in an array that it is not equal to null.
Related Posts
- Pass by Value and Pass by Reference in Java
- Oracle PL/SQL: Is Null / Is Not Null
- Java Class for Sending Email using Java API
- Error 14114: (NULL) is not configured as a distributor
- Code Review Checklist for Java
Tags: Java Error Handling, Java NullPointerException, Null Pointer Exception





But what will happen if the user enters more than three. Is there any exception to handle or we have to check ourselves and display a warning to the user?
Wow… just wow. That’s effing genius!
Assuming your input is null free,
whatif you initialized your array:
Arrays.fill(list,”");