23 September 2010

A small tip on String to avoid NullPointerException

Problem
======
Sometimes the condition in Java class needs to compare between a constant string and a variable.

For example:
your_string_variable.equals(CONSTANT_STRING);

String str1="ABC";
String str2;
str1.equals("ABC");
str2.equals("ABC"); // this statment thr error


this thing throws NullPointerException if your_variable is not initilized....

Solution
======
To avoid this null pointer exception you can re-write the above statement:

CONSTANT_STRING.equals(your_string_variable);

String str1="ABC";
String str2;
"ABC".equals(str1);
"ABC".equals(str2);

No comments:

Post a Comment