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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



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