2

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!

MrD
  • 4,737
  • 9
  • 44
  • 86

4 Answers4

3

"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

Community
  • 1
  • 1
Grijesh Chauhan
  • 55,177
  • 19
  • 133
  • 197
  • @DarioPanada see right hand side of this page **Related**, All are useful for you. Also when you type a question you will find related questions which can save your time to post a question. – Grijesh Chauhan Apr 13 '13 at 19:57
0

Use 'B'. Java is case sensitieve, and you neer to compare a char instead of String

Rob Audenaerde
  • 17,859
  • 8
  • 72
  • 114
0

You need to use the char literal by ':

if(myChar == 'b')

quotes(") represent strings. apostrophes(') represent characters

Shelef
  • 3,417
  • 6
  • 22
  • 27
0

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')
Makoto
  • 100,191
  • 27
  • 181
  • 221