Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identical strings comparison gives me false [duplicate]

I have two identical strings, one in an array and one in a String variable. When I compare these IDENTICAL strings I get false every time. I have debugged and debugged, but I get the same result every time. Here is the code in question

String temp = ""+(num1*num2);
Boolean equal = temp == answers[i];

if(equal) {
    correct[i] = true;
    num_correct ++;
}else{
    correct[i] = false;
}

Again, I have debugged every minor detail of this program and I am 101% sure that the strings are IDENTICAL. Why is Java returning false on comparison?

like image 732
Hubro Avatar asked Oct 06 '10 15:10

Hubro


2 Answers

When you use the == operator in Java with objects, you are attempting to compare object references. That is, is this object handle pointing to the EXACT same object as this other object handle. Unless the strings are interned, this will not work.

Use String.equals(Object) instead:

Boolean equal = temp.equals(answers[i]);
like image 179
jdmichal Avatar answered Nov 06 '22 00:11

jdmichal


You are doing reference comparison, not value comparison. When you use the == operator its checking to see if the references are equal, and they aren't. If you want to check whether the values are equal use the equals method.

boolean equal = temp.equals(answers[i]);
like image 28
Corey Sunwold Avatar answered Nov 06 '22 01:11

Corey Sunwold