Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Im trying to compare two 'char' datatype in java, and am having problems, ive tried equals() and compareTo(), both dont work, any help would be gratly appreciated.
Thanks in advance,
Pamela

I'm pretty new to Java and have not used char, but my book lists it as a Numeric Data Type, along with Byte, Short, Int, etc.
Have you tried ==?

From what I can see .equal() and .compareTo() are the only ways to compare chars. How are putting them into your if or loop statement?

I do not think == would work because it is only comparing if there is the same number of letters, it does not distinguish between individual letters. For example the == would think that 'from' and 'form' where equal with each other.

"Teach Yourself JAVA in 21 Days, Professional Edition", page 60
"The char type is used for individual characters."
"from" or "form" would have to be a String, char array, charBuffer or some such.
Additionally, the only situation where 'from' and 'form' would be considered equal would be if you were comparing 'sets' of characters.

If you are able to fit either 'form' or 'from' into a char type in java, you don't have to learn how to program because you will get rich showing the world how to fit 32 bits of data into 8 bits.
char is a primitive data type, and will hold just one character. The == operator will work beatifully as it will compare the ascii codes of the operands and let you know if they are equal, exactly as it does with ints.
If you desire to compare things like "form" and "from", you should declare them as Strings, not chars, and use statements like
"from".compareTo("form"); and you will get a proper comparison. Good luck,
SN

I am interested because I have the same problem.
I am parsing a String that has commas and about to know when I have a comma.
I have this code that does not work:
char c = myString.charAt(J);
if (c == ",")
counter ++;Sorry, It did work I just change
from
if (c == "," )
to
if (c == ',')

![]() |
![]() |
![]() |

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