Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Java by (900 points)
In Swing, the password field has a getPassword() (returns char[]) method instead of the usual getText() (returns String) method. Similarly, I have come across a suggestion not to use String to handle passwords.

Why does String pose a threat to security when it comes to passwords? It feels inconvenient to use char[].

2 Answers

0 votes
by (13.2k points)

The main reason for character array being preferred over string is the immutable nature of string. What that means is, if the password is stored as plain text then it would be available in the memory until the garbage collector clears it, and since it is immutable, there is no way the content of the string can be changed, changing it would result in entirely different (new) string. 

This leads to the less secure nature of strings as compared to character arrays, as they are stored in plain text and anyone getting a hand on them would have access to raw passwords. Incase of array you could explicitly wipe the data, overwrite the array and raw data is not available anywhere, contrary to string which makes it more vulnerable.

0 votes
by (32.3k points)

If you using plain String, then there are much higher chances of accidentally printing the password to logs, monitors or some other insecure place. And char[] is less vulnerable.

Are you interested to learn Java from basics! Refer to this video on Java provided by Intellipaat:

So, try doing something like this:

public static void main(String[] args) {

    Object pw = "Password";

    System.out.println("String: " + pw);

     pw = "Password".toCharArray();

    System.out.println("Array: " + pw);

}

Prints like this:

String: Password

Array: [C@5829428e

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 9, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...