File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Convert String to char and determining Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Convert String to char and determining" Watch "Convert String to char and determining" New topic

Convert String to char and determining

Garry Meax
Ranch Hand

Joined: Feb 11, 2005
Posts: 31
whether its a specific character.

i declare grade1 as a String. then i convert it to char as follows:


i want to check whether this((char)grade1) is equal or not to 'A'.

so i use,

if((char)grade1 != 'A')

am i right here?
Mehul Sanghvi
Ranch Hand

Joined: Feb 04, 2002
Posts: 134

You cannot typecast a String to char.
String is an object whereas char is a basic data type.

You could try this instead:

Abdulla Mamuwala
Ranch Hand

Joined: Jan 09, 2004
Posts: 225
Hi Gary,

You cannot cast a String to char. This will give you a compile time error. Why dont you make 'grade1' of type String instead of char. If for some reason you have to cast it from String to char type, than I would suggest using the toCharArray() method in the String class. The method will return you a new character array. Than by using some looping mechanism you can extract the required character and than apply your conditional constraints.
Alternately you could also use the charAt(int index) method of the String class to do the conversion, note that the first char value of the sequence is at index zero('0').
Garry Meax
Ranch Hand

Joined: Feb 11, 2005
Posts: 31
thanks guys
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Also, if you know that the String contains only a single char for the grade, you can compare two String objects directly:



Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: Convert String to char and determining
It's not a secret anymore!