Possible Duplicate:
How do I compare strings in Java?
I cant understand why the declared variables is not the same.
ex code:
String firstPart = "F";
String whole = "False";
String connected = firstPart + "alse";
System.out.println(connected == whole);
Now this produce a boolean and I thought it would be 'true' BUT it is not, It comes out as false and I don't understand why.
Can someone explain this?
You are comparing references, not the values.
You'll need to use equals
:
connected.equals(whole);
This
String connected = firstPart + "alse";
creates a new String
object, with a new underlying char array and a new reference.
Consequently when you compare references (using '=='') you won't get a match. If you compare the actual object contents using equals()
then you'll get the result you want (since String.equals()
compares the contents of the underlying char arrays)
You should compare strings using equals()
. Like so:
System.out.println(connected.equals(whole));
When you use "==" to compare the strings it means that you want to compare their reference values but not the values they have, which in this case will return false.
you need to use equals
method which will compare strings based upon the values they are holding..
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