Fast question
I am comparing a String, should I use equals or compareTo? because I though equals distinguish 2 objects of type String and not just their value...
which may cause problems since:
String a = new String("lol");
String b = new String("lol");
are two different objects even if they have the same value?
Whats exactly difference between equals and compareTo implementations in terms of performance and precision?
First of all ==
compares the references to see if the two objects are the same (so ==
is on the object).
Then String.equals()
verify the equality of the content of two strings while String.compareTo()
seek the difference of the content of two strings.
So the two following tests are equivalent:
String str = "my string";
if ( str.equals("my second string")) {/*...*/}
if ( str.compareTo("my second string")==0) {/*...*/}
But, since String.equals
is making a reference check first, it's safe when used against null
, while String.compareTo
will throws a NullPointerException
:
String str = "my string";
if ( str.equals(null)) {/* false */}
if ( str.compareTo(null) {/* NullPointerException */}