RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Advanced
Aug 25, 2009

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 DB
if(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.

Ritesh Patel
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date