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
Printable View
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.
...the optimizer isn't quite that clever:
output: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));
compare: true
compare: false
compare: false
This implies that java has implemented, by round-abouts reliable operator overloadingQuote:
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.
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*
there is also .equalsIgnoreCase() to compare strings and ignore the case