Skip to content
Advertisement

Java – Why can’t I use charAt() to see if a char equals another?

I want to see if a character in my string equals a certain other char value but I do not know what the char in the string is so I have used this:

if ( fieldNames.charAt(4) == "f" )

But I get the error:

"Operator '==' cannot be applied to 'char', 'jav.lang.String'"

But "g" == "h" seems to work and I know you can use '==' with char types.

Is there another way to do this correctly? Thanks!

Advertisement

Answer

This is the correct way to write that:

if ( fieldNames.charAt(4) == 'f' )

In your original version, "f" is a String and fieldNames.charAt(4) is a char, and you cannot compare a String with a char using ==. If you write 'f' instead of "f" (as above) you will be comparing a char with a char.

Note that "g" == "h" is also accepted by the compiler because both "g" and "h" are String objects. However, you shouldn’t do that. You should use "g".equals("h") instead. To understand why, please read How do I compare strings in Java?. (The short version is that someString == otherString comparisons will often give an unexpected answer!)

By contrast 'g' == 'h' is both accepted by the compiler AND correct code.


More background: a Java String literal is surrounded by double quotes, but a char literal is surrounded by single quotes; e.g.

String s = "g";
char c = 'g';

A char value consists of one and only one character1 but String value can contain more than one character … or zero characters.

String s2 = "gg";  valid
char c2 = 'gg';  not valid

String s3 = "";  valid
char c3 = '';  not valid

1 – Actually, calling them characters is technically a stretch. A char … or a value returned by String.getChar is actually an unsigned 16 bit number. But Java natively uses Unicode, and 16 bits is not enough to represent all Unicode code points. It was when Java was designed, but then Unicode added more code planes.

Advertisement