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.

See also  5 Ways to Improve Customer Experience

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist