- Strings are immutable: Strings are immutable in Java and therefore if a password is stored as plain text it will be available in memory until Garbage collector clears it and as Strings are used in String pool for re-usability there are high chances that it will remain in memory for long duration, which is a security threat. Strings are immutable and there is no way that the content of Strings can be changed because any change will produce new String.
With an array, the data can be wiped explicitly data after its work is complete. The array can be overwritten and and the password won’t be present anywhere in the system, even before garbage collection.
- Security: Any one who has access to memory dump can find the password in clear text and that’s another reason to use encrypted password than plain text. So Storing password in character array clearly mitigates security risk of stealing password.
- Log file safety: With an array, one can explicitly wipe the data , overwrite the array and the password won’t be present anywhere in the system.
With plain String, there are much higher chances of accidentally printing the password to logs, monitors or some other insecure place. char is less vulnerable.
//Java program to illustate prefering char arrays
//over strings for passwords in Java
String strPwd =
 charPwd =
"String password: "
+ strPwd );
"Character password: "
+ charPwd );
String password: password Character password: [C@15db9742
- Java Recommendation: Java has methods like JPasswordField of javax.swing as the method public String getText() which returns String is Deprecated from Java 2 and is replaced by public char getPassword() which returns Char Array.
This article is contributed by Kanika Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Convert string to char array in C++
- char* vs std:string vs char in C++
- Convert an ArrayList of String to a String array in Java
- Convert Set of String to Array of String in Java
- Generate all passwords from given character set
- Passwords | Entropy and Cracking
- What is the difference between "char a" and "char a"?
- What's difference between char s and char *s in C?
- Passwords and Cryptographic hash function
- Ideas for Strong Recoverable Passwords
- Saving What Saves Our Passwords – Two-Factor Authentication
- Print * in place of characters for reading passwords in C
- What is the difference between single quoted and double quoted declaration of char array?
- Performance analysis of Row major and Column major order of storing arrays in C
- Difference between const char *p, char * const p and const char * const p