Reputation: 5086
Suppose I have the following code:
String myString = "Hello";
char firstChar = myString.charAt(0);
I then want to check if firstChar has value "B". I tried
if(myChar == "b")
and
if(myChar.equals("b"))
but none of these work.
What solution could I use?
Thanks in advance!
Upvotes: 2
Views: 280
Reputation: 58271
"b"
is not char but string to compare char you should write if(myChar == 'b')
Note:
5 means number
'5' means char
"5" means string
all are different datatypes.
read: How do I compare strings in Java?
==
compares reference equality. and .equals()
tests for value equality.
read also this to check for upper or lower char: Find if first character in a string is upper case, Java
Upvotes: 3
Reputation: 106400
Characters work differently than String
. You can't call methods on them, but you can compare them using ==
.
If you want to compare either case, then you can use this:
if(myChar == 'b' || myChar == 'B')
Upvotes: 0
Reputation: 3827
You need to use the char literal by ':
if(myChar == 'b')
quotes(") represent strings. apostrophes(') represent characters
Upvotes: 0
Reputation: 20019
Use 'B'. Java is case sensitieve, and you neer to compare a char
instead of String
Upvotes: 0