Tuesday, May 20, 2008

What is NullPointerException ?

NullPointerException is the most common exception of the Java world.

It occurs when you try to call method or modify and attiribute of a null object.

Here is an example :

String strObject = null;
int
len = strObject.length();// throws a NullPointerException

The code tried to access a null string's length() method so it is illegal. There is no strObject so there is no length() of it.

To avoid NullPointerException you should check the of object if it is null before accessing it's members.

For example in the jsp code below , we want to get userName from HTTP Post parameters , and print an error message if the length is less than 6 :

String userName = request.getParameter("userName");

if ( userName.length()<6)

out.print("Invalid Username");

return;

}

This code fails when the user in logon page sends an empty string for userName.

The code will be better if we check the object is null before access its method :

String userName = request.getParameter(
"userName");

if ( userName==null || userName.length()<6)

out.print("Invalid Username");

return;

}

Note that if statements exists after the first "true" reached , since this is an "OR" statement and does not run other part of If statement , otherwise userName.length()would throw exception in the if statement.


No comments: