Compare two JPasswordFields in Java before saving?

user1922355 picture user1922355 · Dec 21, 2012 · Viewed 11.3k times · Source

Possible Duplicate:
How to check if JPassword field is null

While creating a login registration form, I am using two password fields. Before saving the data, I want to compare both fields; and if they match, then the data should be saved in file. If not it should open a dialog box. Please can anyone help me.

Answer

Reimeus picture Reimeus · Dec 21, 2012

The safest way would be to use Arrays.equals:

if (Arrays.equals(passwordField1.getPassword(), passwordField2.getPassword())) {
   // save data
} else {
  // do other stuff
}

Explanation: JPassword.getText was purposely deprecated to avoid using Strings in favor of using a char[] returned by getPassword.

When calling getText you get a String (immutable object) that may not be changed (except reflection) and so the password stays in the memory until garbage collected.

A char array however may be modified, so the password will really not stay in memory.

This above solution is in keeping with that approach.