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,986
  • 11
  • 48
  • 90

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
  • 57,103
  • 20
  • 141
  • 208
  • @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
  • 19,195
  • 10
  • 76
  • 121
0

You need to use the char literal by ':

if(myChar == 'b')

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

Shelef
  • 3,707
  • 6
  • 23
  • 28
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
  • 104,088
  • 27
  • 192
  • 230