devxlogo

Comparing Constant Strings with String Variables

Comparing Constant Strings with String Variables

To avoid problems, you should never compare a string variable with a string constant, because string variables may have a null value, in which case your code will throw a NullPointerException.Here’s an example:

String strName = null;strName = getName(); //some call which retrives name from DBif(strName.equals("Ritesh Patel")) {    // some processing.}

The preceding example might raise an exception if the result of the getName() call returns null. Instead, to be safe, always make the comparison the other way around—by comparing the string constant with the string variable:

String strName = null;strName = getName();if("Ritesh Patel".equals(strName)) {  // some processing.}

Following this rule will help you avoid unnecessary NullPointerExceptions and abnormal program termination.

devx-admin

Share the Post: