When should one compare Strings as objects and when should one use their equals method? To make sure, I always use equals, but that doesn't seem very efficient. In what situations can I be certain that string1 == string2 is a safe to use?
Thanks!
You should almost always use equals. You can be certain that string1 == string2 will work if:
It really doesn't happen very often, in my experience.
From what I know of Java, string1==string2 will only be true if the references to those objects are the same. Take a look at the following case
String string1 = new String("Bob");
String string2 = new String("Bob");
string1 == string2; // false, they are seperate objects
string1 = string2;  // asigning string1 to string2 object
string1 == string2; // true, they both refer to the same object
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With