Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in Java, ("string").equals(var) recommended other than (var).equals("string")?

Tags:

java

I have seen most cases developers use first string and after that variable used in .equal operation. What is the reason?

like image 455
user3714383 Avatar asked Dec 01 '22 01:12

user3714383


1 Answers

Because var can be null and var.equals("string") will throw NullPointerException (attempt to call of method on null). On the other hand, "string".equals(null) will just return false.

like image 136
om-nom-nom Avatar answered Dec 05 '22 12:12

om-nom-nom