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?
Because it's the documented behavior of compareTo() (emphasis added):
The natural ordering for a class
Cis said to be consistent with equals if and only ife1.compareTo(e2) == 0has the same boolean value ase1.equals(e2)for everye1ande2of classC. Note thatnullis not an instance of any class, ande.compareTo(null)should throw aNullPointerExceptioneven thoughe.equals(null)returnsfalse.
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 returnfalse.
From the javadoc
Compares this String to another Object. If the Object is a String, this function behaves like compareTo(String). Otherwise, it throws a ClassCastException (as Strings are comparable only to other Strings).
The only other option would be to throw a ClassCastException however, since there is a well defined exception for null references, the NPE is thrown instead.
Executing the following code:
void do()
{
    String s = null;
    System.out.println(s instanceof String); 
}
yields false.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With