Is it more proper to use the equivalent operator or the equals() method to compare the contents of Strings? [duplicate]

StackOverflow https://stackoverflow.com/questions/17621854

Pregunta

I'm reading about the notion of interned strings:

String s1 = "Hi";
String s2 = "Hi";
String s3 = new String("Hi");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s3)); //true

String is an object in Java, but the compiler allows us to use a literal for assigning to a String reference variable, instead of requiring us to use the new operator, because of the ubiquity of strings in programming. The use of the literal for assignments creates an interned string. All interned strings with the same literal point to the same space in memory, thus the equivalent operator is permitted.

It got me wondering, however: would it not be more proper to use the equals() method to compare two string reference variables, given that in Java strings are objects (and not arrays like in other languages) and the contents of objects should be compared using equals(), as the == operator in regards to objects only tells us that they point to the same spot in memory?

Or is it not more proper because the very concept of interned strings makes it clear that one String can only be equivalent (==) to another string if they share the same literal?

If it is more proper, do people commonly use the equals() method regardless, or is it considered overkill?

¿Fue útil?

Solución

Yes equals is the method used to compare the contents of string objects. Using == we can only compare whether the two references point to the same memory location or not. But using equals you can check whether two references hold the same string content, be them at the same memory location or not. Logically speaking, when you are trying to compare two strings, you must be looking for comparing the contents of those strings and not the memory locations of them.

As a practice or almost everywhere string equals method is used for string comparision and not ==

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top