Computing.Net > Forums > Programming > Java Casting/Converting String to Char

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

Java Casting/Converting String to Char

Reply to Message Icon

Name: Jason Humphries
Date: June 4, 2002 at 20:32:34 Pacific
Comment:

Can you cast a String to a char by typing:
String z = "A";
char zz = (char)z;
please help. I get the "inconvertible types" error



Sponsored Link
Ads by Google

Response Number 1
Name: Jeff J
Date: June 4, 2002 at 22:05:13 Pacific
Reply:

That sort of thing won't work in most any language. A string is an array numbers (just known as chars in this case), and a char holds just one number, so they're not compatible. It's no different than trying to cast an array of integers (or any group of integers), to a single integer. Which integer should be used?

In your example, you and I both can see that z only contains a single character, but there's no simple way for the compiler to know z will always contain just one. It only knows that z is an array type, that can hold anywhere from zero to millions of characters.

You can, however, grab a specific char from the string. For example:

char zz = z.charAt(0);


0
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Programming Forum Home


Sponsored links

Ads by Google


Results for: Java Casting/Converting String to Char

Convert int to Char c++ www.computing.net/answers/programming/convert-int-to-char-c/12549.html

How to convert string to a binary www.computing.net/answers/programming/how-to-convert-string-to-a-binary/839.html

convert void* to char www.computing.net/answers/programming/convert-void-to-char-/16145.html