-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,120
  • 4
  • 15
  • 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
  • 25,338
  • 7
  • 55
  • 68
1

I would prefer the latter.

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

You can also read about Yoda Conditions!

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Mohamed Anees A
  • 4,119
  • 1
  • 22
  • 35
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
  • 30,180
  • 9
  • 58
  • 71
0

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

Mikel San Vicente
  • 3,831
  • 2
  • 21
  • 39