Comparing two strings in Java

Possible duplicate:
Java String.equals vs ==

I know this is a dumb question, but why does this code not 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 the content of "editText1" "Sample Text"

+4
source share
5 answers

In Java, two strings (and, in general, two objects) must be compared using equals() , not == . The == operator checks identity (this means: testing if two objects in memory are the same), while the equals() method checks two objects for equality (which means: testing if two objects have the same value), regardless of whether they are two different object. You are almost always interested in equality, not identity.

To fix your code, do the following:

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

Also note that it is recommended that you use the string literal first in the equals() call, so you are safe if the second string is null , avoiding a possible NullPointerException .

+21
source

The correct way to compare 2 objects in java is using the equals() method of Object class And since String is an object in java, it should be compared in the 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());

+1
source

In Java Strings you need to compare with the equals() method:

 String foo = "foo"; String bar = "bar"; if (foo.equals(bar)) System.out.println("correct"); else System.out.println("incorrect"); 
0
source
 ((TextView)findViewById(R.id.textView1)).setText("SampleTest".equals(((EditText)findViewById(R.id.editText1)).getText().toString()) ? "correct!" : "incorrect!"); 

This is a little longer, and maybe the best way to do it..toString () feels weird!

0
source

to compare values ​​for two strings (for equality) you need to use equals, not == (or use equalsIgnoreCase if you don't need case sensitivity).
Using equals will check the contents / values ​​of strings (unlike "==", which will only check if two variables point to the same object - not the same value).

0
source

All Articles