Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String equality in Java

I have seen both of these when checking the equality of two Java String's:

// Method A
String string1;
// ...
if("MyString".equals(string1)) {
    // ...
}

and

// Method B
String string1;
// ...
if(string1.equals("MyString")) {
    // ...
}

My question is: which one is better and more widely used?

like image 952
AniDev Avatar asked Dec 09 '22 11:12

AniDev


1 Answers

If you are sure that string1 can never be null then option 2 is readable and preferred. Otherwise option 1. Intention of option 1 is to avoid potential null pointer.

like image 139
Aravind Yarram Avatar answered Dec 19 '22 17:12

Aravind Yarram