Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 286
Mayron Avatar asked Nov 01 '14 11:11

Mayron


People also ask

Why is charAt not working Java?

The "charAt is not a function" error occurs when we call the charAt() method on a value that is not a string. To solve the error, convert the value to a string using the toString() method or make sure to only call the charAt method on strings.

How do you check if a char is equal to another char in Java?

How do you check if a char is equal to another char in Java? In Java, you can use the char “equals()” method to compare two character values by passing a character as a parameter. It returns a boolean value, “true” or “false”, where true indicates the value and the case is equal, and false denotes its negation.

How do you check if a char equals a char?

But char is not an Object type in Java, it is a primitive type, it does not have any method or properties, so to check equality they can just use the == equals operator.

Can you use charAt and equals?

charAt() returns a char, so the message was telling you that . equals() is not appropriate.


2 Answers

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
like image 195
Madhawa Priyashantha Avatar answered Sep 25 '22 17:09

Madhawa Priyashantha


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

like image 37
And Avatar answered Sep 24 '22 17:09

And