Search code examples
javaarraysswingif-statementjpasswordfield

JPasswordField Turning into String but cannot Compare


Hello what i am trying to do here is to recieve the password the User has entered then compare it with the correct password in a if statement.

public void actionPerformed(ActionEvent event)
{
    String UsersStoredPassword = "hello";
    String UsersEnteredPassword = new String(PasswordField.getPassword());
    String Message = "The Password You Have Entered Is Correct";
    String Message1 = "You Have Entered The Wrong Password";

    if (event.getSource() == PasswordField)
    {
        if (UsersEnteredPassword == UsersStoredPassword)
        {
            JOptionPane.showMessageDialog(null, Message);
        }
        else
        {
            JOptionPane.showMessageDialog(null, Message1);
        }

    }
}

However event thought the user typed in the correct password: "hello" it still shows message1: "You Have Entered The Wrong Password. I have tried doing this:

public class TheHandler implements ActionListener
{
    public void actionPerformed(ActionEvent event)
    {

        String UsersStoredPassword = "hello";
        String UsersEnteredPassword = new String(PasswordField.getPassword());
        String Message = "The Password You Have Entered Is Correct";
        String Message1 = "You Have Entered The Wrong Password";

        if (event.getSource() == PasswordField)
        {
            JOptionPane.showMessageDialog(null, UsersEnteredPassword);
        }
    }
}

and it shows UsersEnteredPassword as typed inside.


Solution

  • if(UsersEnteredPassword == UsersStoredPassword){
    

    to

    if(UsersEnteredPassword.equals(UsersStoredPassword)){
    

    on Objects manipulation

    == means, pointing to the same address? or, its the exactly same object?

    equals compares the content.