Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Converting: char[] array --> String

Tags:

java

string

char

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?

like image 586
Henry Harris Avatar asked Jul 26 '12 22:07

Henry Harris


People also ask

How do I convert a char array to a string in java?

Another way to convert a character array to a string is to use the valueOf() method present in the String class. This method inherently converts the character array to a format where the entire value of the characters present in the array is displayed.

Can we convert string [] to string?

So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.

How do I return a char array to a string?

The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);

Can we convert array to string in java?

Below are the various methods to convert an Array to String in Java: Arrays. toString() method: Arrays. toString() method is used to return a string representation of the contents of the specified array.


1 Answers

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")){
like image 117
Jon Lin Avatar answered Nov 15 '22 22:11

Jon Lin