Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two strings in Java [duplicate]

Possible Duplicate:
Java String.equals versus ==

I know it' a dumb question but why this code doesn't work.

boolean correct = "SampleText"  == ((EditText)findViewById(R.id.editText1)).getText().toString();
    if(correct) ((TextView)findViewById(R.id.textView1)).setText("correct!");
    else ((TextView)findViewById(R.id.textView1)).setText("uncorrect!");  

The point is to check if content of "editText1" is equal to "Sample Text"

like image 724
Pawelnr1 Avatar asked Jun 17 '12 16:06

Pawelnr1


4 Answers

In Java, two strings (and in general, two objects) must be compared using equals(), not ==. The == operator tests for identity (meaning: testing if two objects are exactly the same in memory), whereas the method equals() tests two objects for equality (meaning: testing if two objects have the same value), no matter if they're two different objects. Almost always you're interested in equality, not in identity.

To fix your code, do this:

String str = ((EditText)findViewById(R.id.editText1)).getText().toString();
boolean correct = "SampleText".equals(str);

Also notice that it's a good practice to put the string literal first in the call to equals(), in this way you're safe in case the second string is null, avoiding a possible NullPointerException.

like image 138
Óscar López Avatar answered Nov 09 '22 18:11

Óscar López


In Java Strings have to be compared with their equals() method:

String foo = "foo";
String bar = "bar";
if (foo.equals(bar)) System.out.println("correct");
else System.out.println("incorrect");
like image 1
nkr Avatar answered Nov 09 '22 19:11

nkr


to compare the values for two strings (for equality), you need to use equals, not == (or use equalsIgnoreCase if you do not care about case sensitivity).
Using equals will check the contents/values of the strings (as opposed to "==" which will only check if the two variables point to the same object - not the same value).

like image 1
ali haider Avatar answered Nov 09 '22 19:11

ali haider


The correct way to compare 2 objects in java is using equals() method of Object class And as String is an object in java, it should be compared in same way.

The correct way to compare a String is with,

s1.equals(s2)

So you can use this,

boolean correct = "SampleText".equals(((EditText)findViewById(R.id.editText1)).getText().toString());

like image 1
Kumar Vivek Mitra Avatar answered Nov 09 '22 19:11

Kumar Vivek Mitra