Which among the 2 is better way to compare String?
String str="Hello";
//case 1:
if(str.equals("Hello")){
//case 2:
if("Hello".equals(str))
Which among the 2 is better way to compare String?
String str="Hello";
//case 1:
if(str.equals("Hello")){
//case 2:
if("Hello".equals(str))
I use the case 2
whenever I need to compare with a constant string.
if("Hello".equals(str))
Above avoids NullPointerException
.
Update:-
I don't think there are any performance issues because for CPU it will be same, the order doesn't matter.
But at few places, it eats up the readability.
(5==num)
In the above, you will be reading it as 5 is equal to num
and not num is equal to 5
.
I would prefer the latter.
"Hello".equals(str) //prevents NullPointerExceptions.
You can also read about Yoda Conditions!
Consider this scenario:
String str = null;
//case 1:
if(str.equals("Hello")){
//case 2:
if("Hello".equals(str))
In the above code, case 1 is going to fail but case 2 will not. So the latter one is better.
However, if you're considering performance, then there's no difference between the two.
The second option is safer because it won't throw a NullPointerException if str is null