String Equality in Java

I saw both of them when checking the equality of two Java String :

 // 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?

+4
source share
6 answers

If you are sure that line1 can never be null, then option 2 is readable and preferred. Otherwise, option 1. The intention of option 1 is to avoid the potential null pointer.

+10
source

Method B will end with a NullPointerException on line zero1, while Method A will never throw it. Some authorities claim this "defensive" programming. They influenced me to do this, although it still doesn't come naturally!

You can also write

 if (string1 != null && string1.equals("MyString")) ... 

although tools like FindBugs put this as a possible mistake, assuming you have to make sure that line1 is no longer zero. (Can you rely on the evaluation order?).

So there are different schools of thought.

+3
source

Method A will not throw a null pointer exception. They are not better. It depends on whether you want it to select npe (and you might need this in your overall design).

+3
source

Method a does not throw a NullPointerException and, therefore, is very convenient. It is also widely used.

0
source

Exceptions are for exceptional processing and have more overhead than checking error conditions and processing them using conventional logic. If you've been programming for a decade, NPE is an overeating problem that usually indicates sloppy code. Avoid them using the "constant" .equals (variable), and people who read your code and use it will be happier.

0
source

The second option is more widely used. Nothing is better.

This is the same idea as

 if (1 == x) 

but without any specific reason. but for a different reason. (Null pointer, as others point out).

-2
source

Source: https://habr.com/ru/post/1333852/


All Articles