title: Why does JPasswordField.getPassword() create a String with the password in it?
body: <p>Swing's <a href="http://java.sun.com/javase/6/docs/api/javax/swing/JPasswordField.html" rel="noreferrer"><code>JPasswordField</code></a> has the <a href="http://java.sun.com/javase/6/docs/api/javax/swing/JPasswordField.html#getPassword()" rel="noreferrer"><code>getPassword()</code></a> method that returns a char array. My understanding of this is that the array can be zeroed immediately after use so that you do not have sensitive things hanging around in memory for long. The old way to retrieve the password was to use <code>getText()</code>, which returns a String object, but it has been deprecated.</p>
  
  <p>So, my question is why it is actually being used by Java during the retrieval process using <code>getPassword()</code>??? To be clearer, I was debugging my test app for something else**, I followed the calls and bang... <code>getText()</code> in <code>JPasswordField</code> was called and, of course, a nice String object with my password has been created and now is hanging around the memory.</p>
  
  <p>Try it for yourself:</p>
  
  <pre><code>public class PasswordTest() {
      public static void main(String[] args) {
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          JPasswordField passField = new JPasswordField();
          pass.addActionListener(new ActionListener() {
              public ActionPerformed(ActionEvent evt) {
                  char[] p = passField.getPassword(); // put breakpoint
                  // do something with the array
              }
          });
          frame.add(passField);
          frame.setVisible(true);
          frame.pack();
      }
  }
  </code></pre>
  
  <p>Follow up question: is this 'hidden' use of <code>getText()</code> dangerous in any way? Of course a dedicated attacker WILL get your password if it has compromised the system, I am talking about a less dedicated one ;)</p>
  
  <p>**I came across this while I was looking for a way to actually display some sensitive data on a Swing component without using a <code>String</code> object. Apparently there is no way to do it unless I am willing to rewrite part (all?) of the Swing API.. not gonna happen.</p>