1

I'm a newbie to Java and have a simple question regarding the compareTo() method.

When using the code

String Name1 = "alan";
System.out.println(Name1.compareTo("a"));

String Name2 = "bob";
System.out.println(Name2.compareTo("a"));

String Name3 = "carl";
System.out.println(Name3.compareTo("a"));

I would expect that the output would be 0 1 2 however, instead I'm getting 3 1 2

I know it may seem simple but I'm genuinely puzzled. I would have thought that the letter a in 'alan' would be compared with 'a' and thus result in 0. If someone could just explain I'd be highly appreciative.

I was under the impression that compareTo only took the first letter of 'alan' into equation as it seemed to have done so with 'bob' and 'carl'. If I wanted to only use the first letter, how would I go about this? My intention is to order these names in alphabetical order.

  • 2
    Why `0`? "a" and "alan" are not the same. Why `1`? Why `2`? You need to explain your expectations as the only thing you can expect is a positive number. – Hovercraft Full Of Eels Nov 18 '18 at 13:38
  • I was under the impression that compareTo only took the first letter of 'alan' into equation as it seemed to have done so with 'bob' and 'carl'. If I wanted to only use the first letter, how would I go about this? My intention is to order these names in alphabetical order. – Eugene Thornhill Nov 18 '18 at 13:41
  • Read the answer in the [duplicate question](https://stackoverflow.com/questions/4064633/string-comparison-in-java), but more importantly the [String API](https://docs.oracle.com/javase/10/docs/api/java/lang/String.html) section on compareTo. It will explain all you need to know. – Hovercraft Full Of Eels Nov 18 '18 at 13:43
  • 1
    From the [String API](https://docs.oracle.com/javase/10/docs/api/java/lang/String.html): "Returns: the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument." -- so again all you can expect are 0 or positive or negative numbers. You can't make any assumptions about the actual values of those numbers. – Hovercraft Full Of Eels Nov 18 '18 at 13:45
  • If you want to compare only the first letter, then use `substring(0, 1)` – Hovercraft Full Of Eels Nov 18 '18 at 13:47
  • Got it working, thanks @HovercraftFullOfEels – Eugene Thornhill Nov 18 '18 at 15:20

0 Answers0