Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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?
startsWith()
String
charAt() returns a char. Comparing char and String with .equals() will always return false.
charAt()
char
.equals()
false
You'll need
if('(' == number.charAt(0))
Add a comment
That is because charAt(..) returns char not String. And one of if-clauses in equals in String class is:
charAt(..)
equals
if (anObject instanceof String) { ... }
you can try following code:
if(number.startsWith("(", 0)) { System.out.println("IFFF"); } else { System.out.println("OUT"); }
Or you can put: if(number.charAt(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"); }
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.
startsWith()method ofStringwhich might be easier to understand, what you are doing: docs.oracle.com/javase/6/docs/api/java/lang/…