4
        if ("Submit".equals(cmd)) { //Process the password.
    String UserNameInput=UserName.getText();
    ///////////////////////////////ERROR Pin when printed shows error/////////////////////////////
    char[] PinInput = PinField.getPassword();
    String pinInput=PinInput.toString();
            //for debugging , print PinInput , but it prints garbage
    System.out.println("Pin entered is "+PinInput);
            //pinInput has garabage instead of the Pin that was entered
            //so the function isPasswordCorrect fails to verify UserName & Pin
    if (isPasswordCorrect(UserNameInput,pinInput)) 
              {
               //some tasks
              }
         }
            boolean isPasswordCorrect(String Username,String Pin)
            {
             //verify username & pin 
            }

I need to convert the PinInput from character array to String, so that I can use the function isPasswordCorrect() . When I use toString() method , it produces garbage value , what should I do to convert the value of PinInput to String ?

Gaurav
  • 782
  • 1
  • 12
  • 22

2 Answers2

6

Look at the String API, there is a constructor that accepts a char array.

camickr
  • 321,443
  • 19
  • 166
  • 288
4

@camickr is right. That's not garbage; pinField.getPassword().toString() shows the address of the char[], e.g. [C@fd54d6.

Addendum: String.valueOf(array) or new String(array) will convert the result of getPassword() to a String, but this thwarts the security benefit of returning a char[]. Consider keeping the value local and following the API guidelines: "it is recommended that the returned character array be cleared after use by setting each character to zero."

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • just asking for knowledge (as I got the answer ), is there a way to convert that cha[] array to String ? – Gaurav Jul 27 '10 at 20:31
  • and the String.valueOf(array) method simply uses "new String(array)". It is a convenience method. – camickr Jul 28 '10 at 02:50