Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "F" + "alse" not == "False"? [duplicate]

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?

like image 461
user1501127 Avatar asked Jan 15 '13 13:01

user1501127


4 Answers

You are comparing references, not the values.

You'll need to use equals:

connected.equals(whole);
like image 52
Femaref Avatar answered Nov 13 '22 21:11

Femaref


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)

like image 23
Brian Agnew Avatar answered Nov 13 '22 23:11

Brian Agnew


You should compare strings using equals(). Like so:

System.out.println(connected.equals(whole));

like image 6
Ivaylo Strandjev Avatar answered Nov 13 '22 22:11

Ivaylo Strandjev


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..

like image 1
Pratik Avatar answered Nov 13 '22 21:11

Pratik