Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 226
mihaisimi Avatar asked Dec 06 '22 13:12

mihaisimi


2 Answers

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.

like image 80
Matt Ball Avatar answered Dec 24 '22 15:12

Matt Ball


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.

like image 31
Woot4Moo Avatar answered Dec 24 '22 17:12

Woot4Moo