View RSS Feed

My Java Tips

Avoiding null pointer exception

Rate this Entry
by , 11-01-2011 at 05:26 PM (1040 Views)
One should try avoiding null pointer exception. In case of coding an application that needs high degree of reliability, don't take risks. I will present an example.



Check the following piece of code.


Java Code:
private boolean isNullString(String string) {
return (string.equals(""));
}
It seems a normal piece of code. But still there's a hidden trap here. What is the string which is passed is null? So try to rephrase the code as given below.


Java Code:
private boolean isNullString(String string) {
return ("".equals(string));
}
This should work now without any null pointer exceptions.

Submit "Avoiding null pointer exception" to Facebook Submit "Avoiding null pointer exception" to Digg Submit "Avoiding null pointer exception" to del.icio.us Submit "Avoiding null pointer exception" to StumbleUpon Submit "Avoiding null pointer exception" to Google

Tags: None Add / Edit Tags
Categories
Java SE , Performance

Comments