Monday 6 May 2019

android - Comparing two strings in Java






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"


Answer



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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...