1

I have a string

number="(1234)5678"; 

But the if block is not executed:

if("(".equals(number.charAt(0))) { System.out.println("IFFF"); } else { System.out.println("OUT"); } 

How do I change the boolean expression to execute the if block?

1

5 Answers 5

12

charAt() returns a char. Comparing char and String with .equals() will always return false.

You'll need

 if('(' == number.charAt(0)) 
Sign up to request clarification or add additional context in comments.

Comments

3

That is because charAt(..) returns char not String. And one of if-clauses in equals in String class is:

 if (anObject instanceof String) { ... } 

Comments

1

you can try following code:

if(number.startsWith("(", 0)) { System.out.println("IFFF"); } else { System.out.println("OUT"); } 

Comments

0

Or you can put: if(number.charAt(0)=='(')

Comments

0

The charAt() function always returns char..equals() is used for comparing strings.

Characters are primitives, you can compare them with the "==" operator.

 String number="(1234)5678"; if('(' == number.charAt(0)) { System.out.println("IFFF"); } else { System.out.println("OUT"); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.