-2

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))
Prashant Prabhakar Singh
  • 1,010
  • 4
  • 14
  • 33

4 Answers4

3

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.

Mritunjay
  • 24,184
  • 7
  • 51
  • 67
1

I would prefer the latter.

"Hello".equals(str) //prevents NullPointerExceptions.

You can also read about Yoda Conditions!

Andrew Li
  • 51,385
  • 12
  • 117
  • 139
Mohamed Anees A
  • 3,549
  • 19
  • 33
1

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.

Raman Sahasi
  • 27,745
  • 8
  • 56
  • 69
0

The second option is safer because it won't throw a NullPointerException if str is null

Mikel San Vicente
  • 3,620
  • 1
  • 20
  • 36