I know people have asked this question before, but they didn't use .equals()
. So I am going to ask again, why is that I have two strings, but when I compare them with .equals()
I get false. The two strings are 1234 (passwordField2.getPassword()
and String s = bufferedreader.readLine()
.) I have used s.toCharArray to compare them, and same thing. I tried printing them both out and I got
1234
1234
Does anyone know why this is happening? Thank you!
Looking at the JavaDocs, passwordField2.getPassword()
returns a char[]
.
The following code should work for you:
boolean passwordsMatch = bufferedreader.readLine().equals(
new String(passwordField2.getPassword())
);
This code works as it converts the char[]
to a String that can then be compared to the original String
value.
Edit: As Alex L. states in his answer, JPasswordField
stores passwords as character arrays for security purposes.
As such, a better way to write this code may be:
boolean passwordsMatch = Arrays.equals(
passwordField2.getPassword(),
bufferedreader.readLine().toCharArray()
);