How do you convert a character array to a String?
I have this code

Console c = System.console();
if (c == null) {
    System.err.println("No console.");
    System.exit(1);
}
char [] password = c.readPassword("Enter your password: ");

I need to convert that to a String so I can verify

if(stringPassword == "Password"){
    System.out.println("Valid");
}

Can anyone help me with this?

share|improve this question

25% accept rate
There is a reason char[] is used for passwords over Strings. – Jeffrey Jul 26 at 22:43
feedback

2 Answers

up vote 8 down vote accepted

Use the String(char[]) constructor.

char [] password = c.readPassword("Enter your password: ");
String stringPassword = new String(password);

And when you compare, don't use ==, use `.equals():

if(stringPassword.equals("Password")){
share|improve this answer
1  
You should also add in the bit about not using == to compare string's equality. – jmort253 Jul 26 at 22:10
Thanks, was in the middle of editing when you posted comment. – Jon Lin Jul 26 at 22:11
Ok :) Thanks for the tip! – Henry Harris Jul 26 at 22:12
2  
and as a best practice, if your comparing a variable with a string literal or a constant, always call the .equals method from the string literal or a constant to avoid possible null pointer exception, i.e. "Password".equals(stringPassword) – jay c. Jul 26 at 22:15
Thanks guys. :) I will accept your answer in 8 minutes when it allows me :D – Henry Harris Jul 26 at 22:15
feedback

You'll want to make a new String out of the char[]. Then you'll want to compare them using the .equals() method, not ==.

So instead of

if(stringPassword == "Password"){

You get

if("password".equals(new String(stringPassword))) {
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.