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,427
  • 7
  • 31
  • 59
Mayron
  • 1,836
  • 3
  • 18
  • 44

4 Answers4

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

because "f" is a String and fieldNames.charAt(4) is a char. you should use 'f' for check char

"g" == "h" works because both g and h are Strings

and you shouldn't use "g" == "h" you should use "g".equals("h") instead . you can use == for primitive data types like char,int,boolean....etc.but for the objects like String it's really different. To know why read this

but you can use also

'g' == 'h' 

you should wrap Strings by double quotation and char by single quotation

String s="g";

char c='g';

but char can only have one character but String can have more than one

String s="gg";  valid

char c='gg';  not valid
Community
  • 1
  • 1
Madhawa Priyashantha
  • 9,427
  • 7
  • 31
  • 59
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

This works:

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

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
  • 201
  • 4
  • 12