Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview : Java Equals

Tags:

java

I was asked this question in interview. Which of the following is better to use

 MyInput.equals("Something");    

Or

"Something".equals(MyInput); 

Thanks

like image 993
SuperMan Avatar asked Apr 19 '11 05:04

SuperMan


1 Answers

I would go for

"Something".equals(MyInput); 

in this case if MyInput is null then it won't throw NullPointerException

Here we are sure that the object on which equals() is going to invoke is NOT NULL.

And if you expect NullPointerException from your code to take some decision or throw/wrap it, then go for first.

There is no performance impact

like image 104
jmj Avatar answered Oct 13 '22 21:10

jmj