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?
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.
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.
The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);
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.
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")){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With