Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java equals() ordering

Tags:

java

string

If I try to do a .equals() on a null string in java, a null pointer exception will be thrown. I am wondering, if I am trying to compare if a string is equal to some constant string, can I do the following:

MY_CONSTANT_STRING.equals(aStringVariable)

I know it will work, but is this just really poor code?

like image 201
aeq Avatar asked Aug 05 '10 19:08

aeq


People also ask

Is .equals the same as == Java?

equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects.

Why use .equals instead of == Java?

== should be used during reference comparison. == checks if both references points to same location or not. equals() method should be used for content comparison. equals() method evaluates the content to check the equality.

What is difference between == equals () and compareTo () method?

The 2 main differences are that: equals will take any Object as a parameter, but compareTo will only take Strings. equals only tells you whether they're equal or not, but compareTo gives information on how the Strings compare lexicographically.

How do you do equals in Java?

Method 2: Using equals() method In Java, string equals() method compares the two given strings based on the data / content of the string. If all the contents of both the strings are same then it returns true. If all characters are not matched then it returns false.


1 Answers

This is a standard Java idiom jokingly called a Yoda condition.

Personally I prefer to handle the null case explicitly, but the Yoda way is used a lot and any experienced Java programmer should be able to understand what is going on immediately. It's fine to use.

like image 62
Mark Byers Avatar answered Sep 17 '22 15:09

Mark Byers