Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple if else statement not working [duplicate]

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...

like image 603
Badr Hari Avatar asked Nov 27 '22 22:11

Badr Hari


2 Answers

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.

like image 101
Jon Skeet Avatar answered Nov 30 '22 12:11

Jon Skeet


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

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

string::equals reference

like image 28
Mahesh Avatar answered Nov 30 '22 12:11

Mahesh