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?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
Henry Harris
  • 620
  • 4
  • 7
  • 18
  • There is a [reason](http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords) `char[]` is used for passwords over `String`s. – Jeffrey Jul 26 '12 at 22:43

3 Answers3

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")){
Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • 1
    You should also add in the bit about not using `==` to compare string's equality. – jamesmortensen Jul 26 '12 at 22:10
  • Thanks, was in the middle of editing when you posted comment. – Jon Lin Jul 26 '12 at 22:11
  • 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 '12 at 22:15
  • Thanks guys. :) I will accept your answer in 8 minutes when it allows me :D – Henry Harris Jul 26 '12 at 22:15
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))) {
corsiKa
  • 81,495
  • 25
  • 153
  • 204
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!

Shrey
  • 671
  • 7
  • 14
  • Not only that, but char[] is preferred for passwords anyway. http://stackoverflow.com/questions/8881291/why-is-char-preferred-over-string-for-passwords – Gaʀʀʏ May 26 '14 at 19:14