-
== 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:
Code:
String s1="computer";
String s2="computer";
System.out.println("compare: "+(s1==s2));
String s4="computer";
String s5="COMPUTER";
String s6=s5.toLowerCase();
System.out.println("compare: "+(s4==s5));
System.out.println("compare: "+(s4==s6));
output:
compare: true
compare: false
compare: false
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)
This implies that java has implemented, by round-abouts reliable operator overloading
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.
eschew obfuscation
-
o alright. makes sense
thanks
-
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,
always.
My point here being that this random equality should never be utilized in code
*shudder*
Last edited by sjalle; 05-19-2005 at 05:36 AM.
eschew obfuscation
-
there is also .equalsIgnoreCase() to compare strings and ignore the case
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|