It's not a secret anymore!*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Convert String to char and determining" Watch "Convert String to char and determining" New topic
Author

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:

(char)grade1

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

so i use,

if((char)grade1 != 'A')
{
s.o.pln("No")
}
else
{
s.o.pln("Yes")
}

am i right here?
Mehul Sanghvi
Ranch Hand

Joined: Feb 04, 2002
Posts: 134
Hi,

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

You could try this instead:


Mehul.
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:


HTH

Layne


Java API Documentation
The Java Tutorial
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Convert String to char and determining
 
Similar Threads
Convert "\n" to char '\n'
Assignment Java-1b
Convert char array into a string
substring()
convert String to char