This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Creating a String from a char array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Creating a String from a char array" Watch "Creating a String from a char array" New topic
Author

Creating a String from a char array

samyukta rao
Greenhorn

Joined: Dec 02, 2012
Posts: 5
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

Joined: Sep 28, 2012
Posts: 75

Check the String class. There's a constructor that takes in a char array and converts it to a string.


Da mihi sis bubulae frustum assae, solana tuberosa in modo Gallico fricta ac quassum lactatum coagulatum crassum.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14278
    
  21

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
samyukta rao
Greenhorn

Joined: Dec 02, 2012
Posts: 5
Thank you! Helped a lot!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Creating a String from a char array