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 whileString.compareTo()seek the difference of the content of two strings.So the two following tests are equivalent:
But, since
String.equalsis making a reference check first, it’s safe when used againstnull, whileString.compareTowill throws aNullPointerException: