char[] cannot be converted to String

2.4k views Asked by At

I was trying to set the password entered in a JPasswordField and this error appeared:

"Incompatible types: char[] cannot be converted to String"

            dts.setSalary(Double.parseDouble(txtSalary.getText()));
            selected=chgAccess.getSelectedIndex();
            dts.setAccess_number((String)chgAccess.getItemAt(selected));
            dts.setLogin(txtLogin.getText());
            //HERE
            dts.setPassword((String)txtPassword.getPassword());

How can I fix it?

extra question: then it's supposed to go as a VARCHAR type in my database, will it work? I mean, I have created the spaces in the database for text not for passwords; I didn't find a datatype password in MySQL.

2

There are 2 answers

1
Mureinik On

getPassword() returns a char[] - it cannot be simply cast to a java.lang.String. You could, however, construct a new String for this char array:

dts.setPassword(new String(txtPassword.getPassword()));

Or, better yet:

dts.setPassword(String.valueOf(txtPassword.getPassword()));
0
Reimeus On

getPassword returns a char array for a good reason - to prevent any lookup of the String due to the difficulty in erasing String content in memory. Instead I suggest salting the password and storing the hash in the database.