How does a.compareTo(b) works when it comes to Strings with numbers? Is it comparing only first digit (their unicode value) of the number and doesn't care about the rest (ie. not summing unicode value of each digit)? Because using the method isGreaterThan - "22" is not greater than "3" (while obviously integers 22 > 3). And passing ""22".compareTo("3") shows -1 (so I understand that their unicode value differs only by 1 even though 22 is two digit number).
How does a.compareTo(b) work with numbers?
You must be signed in to leave a comment
8 August 2019, 20:07
OK, so if anyone else was wondering the same thing the anwser is - method compareTo(String anotherString) in String class is comparing each character in both Strings. So in String a = "1239" String b = "124" it checks value of every char so a.charAt(0) with b.charAt(0), a.charAt(1) with b.charAt(1) and so on. If values on any point are unequal it stops checking the rest of characters. Therefore in above example string a ("1239") is "smaller" than "124" because unicode value of 3 is smaller than 4. It doesn't check the last char. The same goes with 22 and 3. What is the most important - do not use this method to compare strings with numbers :)