6

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!

Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
Mayron
  • 2,146
  • 4
  • 25
  • 51

3 Answers3

23

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
2

I was having the same problem, but I was able to solve it using:

if (str.substring(0,1).equals("x") )

the substring can be used in a loop str.substring(i, i + 1)

charAt(i).equals('x') will not work together

And
  • 21
  • 1
0

.equals() can still be used, but you have to remember that chars require apostrophes(') instead of quotes("). For example: someChar.equals('c') is valid for chars and someString.equals("c") is valid for strings.

M A F
  • 291
  • 4
  • 14
  • While `someChar.equals('c')` is technically correct code, it is doing unnecessary auto-boxing. That may involve a runtime overhead (depending on how smart the JIT compiler is). – Stephen C Jan 21 '23 at 07:57