12

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?

1
  • There is a reason char[] is used for passwords over Strings. Commented Jul 26, 2012 at 22:43

3 Answers 3

25

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")){
Sign up to request clarification or add additional context in comments.

4 Comments

You should also add in the bit about not using == to compare string's equality.
Thanks, was in the middle of editing when you posted comment.
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)
Thanks guys. :) I will accept your answer in 8 minutes when it allows me :D
6

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))) {

Comments

0

Although not as efficient you could always use a for loop:

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

for(i = 0; i < password.length(); i++){
    str += password[i];
}

This is a very simple way and requires no previous knowledge of functions/classes in the standard library!

1 Comment

Not only that, but char[] is preferred for passwords anyway. stackoverflow.com/questions/8881291/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.