Reputation: 1999
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?
Upvotes: 4
Views: 8283
Reputation: 719239
It is generally understood that the Java SE class library documentation explicitly states when null
is a valid parameter. When there is no mention of null
being a valid argument, you should assume that it is not, and that an exception may be thrown immediately, or later one.
And in this case, the javadoc for the Comparable
interface specifically states that null
is NOT a valid parameter for Comparable,compareTo
. (You can get there from the String.compareTo
javadoc by clicking the "Specified by" link.)
Upvotes: 1
Reputation: 359966
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 ife1.compareTo(e2) == 0
has the same boolean value ase1.equals(e2)
for everye1
ande2
of classC
. Note thatnull
is not an instance of any class, ande.compareTo(null)
should throw aNullPointerException
even 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
.
Upvotes: 11
Reputation: 24336
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.
Upvotes: 3