mihaisimi
mihaisimi

Reputation: 1999

String compareTo

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

Answers (3)

Stephen C
Stephen C

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

Matt Ball
Matt Ball

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 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.

Upvotes: 11

Woot4Moo
Woot4Moo

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

Related Questions