views:

23

answers:

2
        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 ?

A: 

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

camickr
Thanks , I found it public String(char[] value)
Gaurav
+1  A: 

@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
@trashgod , just asking for knowledge (as I got the answer ), is there a way to convert that cha[] array to String ?
Gaurav
@Gaurav: `String.valueOf()`.
trashgod
@trashgod , Thanks :)
Gaurav
and the String.valueOf(array) method simply uses "new String(array)". It is a convenience method.
camickr