*
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 Android Security Essentials Live Lessons this week in the Android 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: 72

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: 14074
    
  16

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 7 API documentation
Scala Notes - My blog about Scala
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
 
Similar Threads
java.sql.date to string
problem in html:image
How to save default text in notepad
String variables and Int variables
cast argument '0' to 'short' error