== and .equals
what exactly is the difference when comparing strings from == and .equals()
because when comparing 2 string variables that both contained the word computer with == it returned true
The '==' operator compares object identity, i.e. that the two references point to the same object instance. The equals() method compares the value (contents) of the objects referenced.
In the case of Strings, the compiler optimizes String usage by sharing a single instance of identical string literals (possible because Strings are immutable). This means that identical Strings will always compare equal with both '==' and equals(). In other word, two identical string literals will have identical contents (equals method) and, due to behind-the-scenes optimization, will actually be the same object instance ('==' operator).
It is good practice always to use the appropriate operator or method (usually the equals() method) when comparing objects rather than rely on a 'hidden' compiler optimization.
Not quite true....
...the optimizer isn't quite that clever:
This implies that java has implemented, by round-abouts reliable operator overloading
two identical string literals will have identical contents (equals method) and, due to behind-the-scenes optimization, will actually be the same object instance ('==' operator)
for the String class. As it appears this only "works" for Strings, in
closely nested code.
Last edited by sjalle; 05-16-2005 at 12:08 PM.
o alright. makes sense
Yeah, '==' usually involves the use of primitive types (int, boolean, double, etc...). .equals() is a method (notice the parentheses haha), therefore it is invloved with an object, in this case String.
For object instances the "==" always goes for the pointer value, the address,
My point here being that this random equality should never be utilized in code
Last edited by sjalle; 05-19-2005 at 05:36 AM.
there is also .equalsIgnoreCase() to compare strings and ignore the case
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL