Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Creating a String from a char array

 
samyukta rao
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
getPassword() returns a char array. If i type cast it into a String variable and try to print it it doesnt seem to work :/ any idea why?
How do i store the password entered in a String variable and pass it as a parameter to a method that takes in String parameters?
 
Aj Prieto
Ranch Hand
Posts: 75
Android Chrome Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check the String class. There's a constructor that takes in a char array and converts it to a string.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15280
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
samyukta rao wrote:If i type cast it into a String variable and try to print it it doesnt seem to work :/ any idea why?

Because a char array is not a String, and casting it does not automatically convert it into a String.

Casting does not automatically convert objects. The only thing that a cast does, is tell the compiler "I have an object here and I know better than you what kind of object this is, so I'm telling you what it is, don't complain about it". But when you run the program, Java will check if the object you're casting is in fact an instance of the type you're casting to. If it is not, you get a ClassCastException. Java is not going to automatically convert the object from one kind to another kind for you.

Aj Prieto has already given you the answer to your question. But there's a special reason why getPassword() returns a char array and not a string. It has to do with security. Check the API documentation of the getPassword() method, where this is explained.
 
samyukta rao
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you! Helped a lot!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic