Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between string.equalsIgnoreCase(object.string) vs object.string.equalsIgnoreCase(string)

Let's say I have a class:

public class MyClass {
    String locale;

    public String getLocale(){
        return this.locale;
    }

    public setLocale(String locale){
        this.locale = locale;
    }
}

Now I have been told that there is a difference in following statements

  1. myClass.getLocale().equalsIgnoreCase("en")

  2. ("en").equalsIgnoreCase(myClass.getLocale())

I have been trying to find the search for it but unable to do so. Can anyone help me with an explanation of what is the difference?

Is there a particular difference in execution time? And also which of these two is the best practice

like image 296
Anas Avatar asked Nov 08 '25 09:11

Anas


2 Answers

myClass.getLocale().equalsIgnoreCase("en") throws NullPointerException when myClass.locale is null.

("en").equalsIgnoreCase(myClass.getLocale()) does not compile.

If you are talking about "en".equalsIgnoreCase(myClass.getLocale()), it works fine when myClass.locale is null. false will be returned.

like image 117
xingbin Avatar answered Nov 10 '25 01:11

xingbin


The only difference I spot is that in the first example the statement myClass.getLocale() is not null-safe, thus somehow might return null and it would lead to the NullPointerException.

The second one is safe since you call a method on "en", which is never null and will not fail even if you pass a null to the method with myClass.getLocale().


Edit: Both of the explanations assume that the myClass is not null itself, thus only getLocale() would fail. Noone of the solutions is null-safe in case the myClass is null - then the NPE will be thrown anyway. (@davidxxx)

like image 27
Nikolas Charalambidis Avatar answered Nov 09 '25 23:11

Nikolas Charalambidis



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!