Henry Harris
Henry Harris

Reputation: 630

Java Converting: char[] array --> String

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?

Upvotes: 12

Views: 25443

Answers (3)

Shrey
Shrey

Reputation: 671

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!

Upvotes: 0

corsiKa
corsiKa

Reputation: 82559

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

Upvotes: 6

Jon Lin
Jon Lin

Reputation: 143876

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

Upvotes: 25

Related Questions