Why Char array is preferred over String for storing password?

Asked 27-Feb-2018
Viewed 368 times

1 Answer


0

“char[] array over a string in java”
Use char [] array for storing any type of password because String objects are immutable (means can’t be modifiable ) objects in java it stored the password as a plain text format as well as it saves the string
in memory, for a long duration of time. And there is no any possibility to modify the content of string object because if any changed occur then the new string will we produced. 


Benefit for storing the password in char[] array, the data will be cleared (wiped) explicitly after the whole process is completed. And if any change occurs then the character will be overwritten in the memory.

Here we demonstrate the simple example, for storing the password char[] array over the string objects-

public class CharOverString
{
 public static void main(String[] args)
 {
  String strPwd = "Mindstick";
  char[] charPwd = new char[] {'M','i','n','d','s','t','i','c','k'};
  System.out.println("String Password: " + strPwd );
  System.out.println("Character Password: " + charPwd );
 }
}

Output :
String Password: Mindstick
Character Password: [C@2a139a55


"Thanks!!! for Reading"