Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between these two appraoch in calling equals method?

Tags:

java

Approach one.

if (graphType.equals("All") || graphType.equals("ALL"))

Aprroach two.

if ("All".equals(graphType) || "ALL".equals(graphType))

What is the difference between these two approaches? Why the below one is better?

like image 506
John Avatar asked Dec 09 '25 22:12

John


2 Answers

The second one is better, as if graphType is null, the first code snippet will throw a NullPointerException.

Note that you can simplify your code using "ALL".equalsIgnoreCase(graphType) (if you accept values such as AlL or aLL...)

Edit regarding your comment:

If graphType is null, in the first case, you will get a NullPointerException. In the second case, the evaluation of the equals method will be false, as "someString".equals(null); always returns false:

Here is the code of the String.equals(String) method:

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = count;
        if (n == anotherString.count) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = offset;
            int j = anotherString.offset;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                    return false;
            }
            return true;
        }
    }
    return false;
}

(source)

The interesting line is if (anObject instanceof String) {. When you call the instanceof statement on a null object, this test always returns false. That's why "anyString".equals(null); will return false.

like image 184
Romain Linsolas Avatar answered Dec 12 '25 13:12

Romain Linsolas


I feel the need to present a contrarian viewpoint to the accepted answer:

The first one is better, precisely because it will throw a NullPointerException in the case where graphType is null.

Generally, if an unexpected condition is found, you want to halt and throw an Exception as early as possible, otherwise you may continue to execute the program in an invalid state and the bug may become fiendishly difficult to track down.

This is sometimes referred to as the "fail-fast" principle.

like image 37
mikera Avatar answered Dec 12 '25 12:12

mikera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!