Java String/Char charAt() Comparison

Kcits picture Kcits · Oct 17, 2016 · Viewed 22.1k times · Source

I have seen various comparisons that you can do with the charAt() method.

However, I can't really understand a few of them.

String str = "asdf";
str.charAt(0) == '-'; // What does it mean when it's equal to '-'?


char c = '3';
if (c < '9') // How are char variables compared with the `<` operator?

Any help would be appreciated.

Answer

Peter Lawrey picture Peter Lawrey · Oct 17, 2016

// What does it mean when it's equal to '-'?

Every letter and symbol is a character. You can look at the first character of a String and check for a match.

In this case you get the first character and see if it's the minus character. This minus sign is (char) 45 see below

// How are char variables compared with the < operator?

In Java, all characters are actually 16-bit unsigned numbers. Each character has a number based on it unicode. e.g. '9' is character (char) 57 This comparison is true for any character less than the code for 9 e.g. space.

enter image description here

The first character of your string is 'a' which is (char) 97 so (char) 97 < (char) 57 is false.