Monday, September 5, 2022

Java Tips - Use StringUtils to Compare Strings

 

Scenario

Wrapper classes come with a bunch of methods which are very easy to use in practice. When we literally assign a value to this kind of objects, these methods work well in a convenient and intuitive way. But if they take values from a SQL select result, they will become nullable objects when their corresponding fields in the database table are nulls. This causes a NullPointerException exception during runtime.

StringUtils can be used as an alternative to avoid the potential defect.


Example

 
import org.apache.commons.lang3.StringUtils;

public class App 
{
    public static void main( String[] args )
    {
    String strA = "abcd";
    String strB = "ABcd";
    String strC = "abcd";
    String strNull = null;
   
    System.out.println( strB.replace("AB", "ab").equals(strA));
   
    try {
    strNull.equals(strA);
    } catch (NullPointerException ex) {
    System.out.println(ex);
    }
   
        System.out.println( StringUtils.equals(strA, strB) );
        System.out.println( StringUtils.equals(strA, strC) );
        System.out.println( StringUtils.equals(strNull, strA) );
    }
}

Output:

true
java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "strNull" is null
false
true
false

No comments:

Post a Comment

React - Makeover in React: W3Schools How To

When it comes to building a React app, I get used to searching for a UI library to build the front pages, a straightforward way to achieve f...