3

Such as if I were to compare the Strings "Hello" and "World".

How does it know Hello is greater than World?

The only thing I can come up with is, maybe it uses the ASCII Table as reference?

Thanks for the help!

ekeitho
  • 109
  • 1
  • 2
  • 8

2 Answers2

5

it compares two strings lexographically. check here in the String API.

If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string.

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
PermGenError
  • 45,977
  • 8
  • 87
  • 106
2

All uppercase are preceding lowercase so:

"Be".compareTo("ay");

will return a negative value, which means "less-than".

Mordechai
  • 15,437
  • 2
  • 41
  • 82
  • and what if I have more than 2 strings in list. How does comparison takes place? I mean index wise (0,1) (1,2) – Govinda Sakhare Mar 25 '16 at 10:16
  • The code you've included returns "-31". `compareTo` returns the non-zero ASCII difference of the two strings. – Gaurang Tandon Feb 24 '17 at 04:01
  • @GaurangTandon Thanks. Edited post. – Mordechai Feb 24 '17 at 18:05
  • I always thought that *preceding* means that uppercase has a *higher* priority than lowercase which makes `"Be".compareTo("ay")>0` :( – He Yifei 何一非 May 01 '17 at 13:51
  • @Arefly Yeah that's confusing, but if you look at it in terms of "less-than", "equals-to" and "greater-than" things are easier to remember. This is how it is described in the [Javadoc](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html#compareTo-T-). – Mordechai May 01 '17 at 18:17