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
myClass.getLocale().equalsIgnoreCase("en")
("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
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With