Wednesday, 21 December 2016

Null/Equality/Empty Check in String

 If you are checking two references  for equality/empty:

Make sure that null check must appear first and then invoke equals () on String to avoid NullPointerException.

If (str == null && str.equals(str1))

If you are checking constant literal against string then make sure literal should be on the left side in order to avoid additional null check :

If (CONSTANT_VALUE.equals(str))

CONSTANT_VALUE is a final variable and must initialized with some value so we can skip null check for the str variable.

If you are checking null or empty then make sure that the following syntax :

if(str1!= null && !(str1.isEmpty()))

No comments:

Post a Comment