Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to compare Strings which could be null [duplicate]

Tags:

java

string

I was just wondering if there is a better way to do this. i feel it might be inefficient. Problem is for DB reasons i need to compare strings which can sometimes be null or not.

public static boolean compareStrings(String str1, String str2){

    if(str1 == null && str2 == null) return true;

    if(str1 != null && str2 != null){
        if(str1.equals(str2))
            return true;
    }

    return false;
}
like image 783
Maurycy Avatar asked Dec 01 '11 05:12

Maurycy


People also ask

How do you compare two NULL values?

The compare() method in StringUtils class is a null-safe version of the compareTo() method of String class and handles null values by considering a null value less than a non-null value. Two null values are considered equal.

Can we compare two NULL values?

Comparing NULL values Since you can't use a equality operator in the WHERE clause (remember, NULL values can't be equated or compared), the right way to compare NULL values is to use the IS and IS NOT operators.

How do you compare NULL and NULL?

In SQL null is not equal ( = ) to anything—not even to another null . According to the three-valued logic of SQL, the result of null = null is not true but unknown. SQL has the is [not] null predicate to test if a particular value is null .


1 Answers

The usual idiom is this:

return (str1 == null ? str2 == null : str1.equals(str2));
like image 187
Taymon Avatar answered Nov 10 '22 12:11

Taymon