Tuesday, 22 May 2012

Most Common Bugs in Java

1. Null pointers

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 act in arguments we mentioned the number'3'


    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.

No comments:

Post a Comment