-3

Please check the following code snippet from button's onClick event handler.

The if statement does not execute even though its TRUE (because of relational operators == and && maybe)... but works fine when string method( .contains() ) used as shown at the end.

EditText uname = (EditText)findViewById(2);
EditText pwd = (EditText)findViewById(3);
TextView msg = (TextView)findViewById(4);

String a = uname.getText().toString();
String b = pwd.getText().toString();

if(a==("afnan")&& b==("secret")){
     msg.setText("abc");
 }else {
      msg.setText("xyz " + a + b); // concatenated a and b to see their values and they are same as in IF statement so why does ELSE always get executed but not IF?
   }

Replacing relational operators with the following works fine but if statement gets true for "afnanaaaaa" since it does contain "afnan" but not EXACLTY contain "afnan":

if(a.contains("afnan")&& b.contains("secret")){
                    msg.setText("Welcome !!!");
     }else if (a!= "afnan" && b!= "secret"){
                msg.setText("xyz ");
      }

HELP PLEASE !!!!!!!!!!

  • 1
    @yshavit, that should be a hint given on the question page! – ChiefTwoPencils Sep 16 '15 at 19:39
  • @yshavit `not working correctly` === `not understood correctly`. But then if that happens a lot that people are confused by it, maybe the operator is not defined as it should have been. – njzk2 Sep 16 '15 at 20:16
  • "misunderstood"... thats why asked.... you dont have to be mean about it -_- – noobdroid Sep 16 '15 at 20:29

1 Answers1

0

You need to understand that Java compare by reference rather than by value in this case. The following code is displays the correct solution:

if(a.equals("afnan")&& b.equals("secret")){
     msg.setText("abc");
 }else {
      msg.setText("xyz " + a + b); // concatenated a and b to see their values and they are same as in IF statement so why does ELSE always get executed but not IF?
   }

Ordinary objects for comparison is to use the method equals(). (etc. a.equals(b)) For arrays and some class need static method. You may want to improve basics of Java with the help of books. About it (equals) writes in the early chapters.

user2413972
  • 1,355
  • 2
  • 9
  • 25