5

I have a simple password protection. I do it like this:

EditText editText1 =  (EditText) findViewById(R.id.editText1);
String Password = editText1.getText().toString();
if(Password == "a"){
  Toast.makeText(getApplicationContext(), "Success" + Password, Toast.LENGTH_SHORT).show();
} else {
  Toast.makeText(getApplicationContext(), "Failure" + Password, Toast.LENGTH_SHORT).show();
}

I have edittext and button. If user is typing in "a", toast should say success. But it is always saying failure. I don't understand what is wrong in my code...

Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
Badr Hari
  • 8,114
  • 18
  • 67
  • 100
  • cut down on the drinking and you'll have different friends! :) Just kidding, but you might want to brush up on the differences. I'd recommend a skimming http://download.oracle.com/javase/tutorial/java/index.html as you already know how to program, you just need to learn the language. – Edwin Buck Mar 16 '11 at 21:23
  • 1
    Thank you, thank you everyone... for your kindness and not laughing at me. I do my best!!! – Badr Hari Mar 16 '11 at 21:27

5 Answers5

21

In Java, using == for non-primitive expressions will always compare object references. You're asking whether Password refers to the exact same object as the string literal "a".

Use either:

if (Password.equals("a"))

or

if ("a".equals(Password))

These will call the String.equals(Object) override, which determines whether two references refer to equal String objects - i.e. the same logical sequence of characters.

The former will throw an exception if Password is null; the latter won't. Don't treat this as a suggestion to always use the latter form - if Password shouldn't be null, then an exception may well be better than continuing in an unexpected state.

I'd also encourage you to be consistent with your variable names - typically local variables are camelCased, so you'd use password instead of Password.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
5

You need to use equals method. Not == for comparison of strings. So, you should be doing -

if( Password.equals("a") )
{
    // ....
}    

string::equals reference

Mahesh
  • 34,573
  • 20
  • 89
  • 115
2

Try this:

if(Password.equals("a"))
{ 
...
}
kjl
  • 912
  • 2
  • 9
  • 15
0

== does a reference check, i.e. it checks if the two strings are physically the same object in memory. They might be (since Java optimises some strings so they are) but you should never rely on this.

equals() checks whether the strings are meaningfully equal, i.e. have the same characters, and this is what you want pretty much 100% of the time.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216
0

In Java...

Object comparison --> x.equals(y)
reference comparison --> x == y
Edwin Buck
  • 69,361
  • 7
  • 100
  • 138