== tests object references, .equals() tests the string values.
Sometimes it looks as if
== compares values, because Java does some behind-the-scenes stuff to make sure identical in-line strings are actually the same object.
For example:
String fooString1 = new String("foo");
String fooString2 = new String("foo");
// Evaluates to false
fooString1 == fooString2;
// Evaluates to true
fooString1.equals(fooString2);
// Evaluates to true, because Java uses the same object
"bar" == "bar";
But beware of nulls!
== handles null strings fine, but calling .equals() from a null string will cause an exception:String nullString1 = null;
String nullString2 = null;
// Evaluates to true
nullString1 == nullString2;
// Throws an Exception
nullString1.equals(nullString2);
##############################################################
Disclaimer: The Best answers from stackoverflow.com has been listed here.
No comments:
Post a Comment