String compareTo

java, null, nullpointerexception

Solution

Because it's the documented behavior of `compareTo()` (emphasis added):

The natural ordering for a class `C` is said to be consistent with equals if and only if `e1.compareTo(e2) == 0` has the same boolean value as `e1.equals(e2)` for every `e1` and `e2` of class `C`. Note that `null` is not an instance of any class, and `e.compareTo(null)` should throw a `NullPointerException` even though `e.equals(null)` returns `false`.

As for `.equals()` returning `false` instead of NPEing, again, it's in the documentation:

For any non-null reference value `x`, `x.equals(null)` should return `false`.

Problem

Does anybody know why `String.compareTo` is not programmed to behave more graciously in regards to a `null` parameter? In my opinion the next sequence should return "1" or at least the javadoc should be more specific in regards to the NPE. `equals()` returns `false` in this case and I guess `equals` and `compareTo` should be consistent. E.g. ``` String nullString = null; System.out.println ("test".equals(nullString)); System.out.println ("test".compareTo(nullString)); ``` Is throwing a NPE: ``` false Exception in thread "main" java.lang.NullPointerException at java.lang.String.compareTo(String.java:1177) ``` To add to it. If you were to make this compareTo in your code, would have you verified for nulls?

Original source

Related problems