0

I have a simple piece of code to validate a username and a password.

    public boolean isValid(String u, String p) {
    if (u=="admin" && p=="password1") {
        return true;
    } else if (u=="user" && p=="password2") {
        return true;
    } else {
        return false;
    }

}

I've tried debugging it, and when it runs, u has the value "admin" and p has the value "password1", but it just skips the first condition. I must have done something wrong, but I can't figure out what.

Gustaf Svensson
  • 643
  • 1
  • 7
  • 11
  • Classical mistake... You don't test string equality using `==`; use `.equals()` instead: `if ("user".equals(u))` etc – fge Oct 28 '14 at 11:33
  • you should use the .equals method for comparison of strings – Harry Oct 28 '14 at 11:33

1 Answers1

1

== should not be used for String comparison. Use equals() instead.

Andrea
  • 6,032
  • 2
  • 28
  • 55