Advertisement

Udemy WW Udemy WW

Wednesday, 18 January 2012

Why char[] array is prefere over String to store password in JAVA ?


7 comments:

  1. String is a emutable class which remain in memory untill garbage collection is not performed. whereas character array is mutable and its value can be altered with other value for security reason.

    ReplyDelete
  2. ok then if we reinitialize a string to null. what will happen?...

    ReplyDelete
    Replies
    1. because String object is emutable it remains in memory until it is not removed by garbage collector,so reinitialize it to null will not improve security,it can read by hacker.

      Delete
    2. @ratnesh reinitializing it to null will not solve the problem.you just make that object eligible for garbage collector.String object is immutable it can not be altered.
      Suppose by chance you create the another String Object using same string literal it may return same object(Interned String). just get look the following example:
      String s="password";
      String r="password";
      System.out.println(s==r) print true bcoz both have reference of same object.

      Delete
  3. For the above example s and r are equal because they are stored as literals, not as objects.String declared as String s="password" are stored in the string pool and it reuses them.

    ReplyDelete
  4. String stores it's values in string pool which cleans out only with GC. where char doesn't store anything permanently . String stores values as text where char values can be stored as encrypted , so password stealing is difficult with char.

    ReplyDelete

Advertisement

Udemy WW