Check password fields with each other

0

How do I validate two password fields if both are the same?

if(pfSenha.getPassword() == pfCSenha.getPassword()) {
    JOptionPane.showMessageDialog(null, "Senhas conferem!");
} else {
    JOptionPane.showMessageDialog(null, "Senhas não conferem!");
}

I've tried ...

if(new String(pfSenha.getPassword()) == new String(pfCSenha.getPassword())) {
    JOptionPane.showMessageDialog(null, "Senhas conferem!");
} else {
    JOptionPane.showMessageDialog(null, "Senhas não conferem!");
}

How can I resolve?

    
asked by anonymous 09.12.2015 / 12:58

1 answer

2

The problem with your code is the == operator.

In Java == compares if two objects point to the same reference (only for non-primitive types, of course). In your case, you should use the method .equals()

if(new String(pfSenha.getPassword()).equals(new String(pfCSenha.getPassword()))) {
    JOptionPane.showMessageDialog(null, "Senhas conferem!");
} else {
    JOptionPane.showMessageDialog(null, "Senhas não conferem!");
}

See: What's the difference between ".equals" and "=="?
How to Compare Strings in Java?

    
09.12.2015 / 13:03