Undocumented String.compareTo(null) NPE?
Asked Answered
S

1

25

The following little test throws an NPE:

public class Test {

    public static void  main(String[] args) {

        String a = "a";
        String b = null;

        System.out.println(a.compareTo(b));

    }

}

Yet, the Javadoc of compareTo() does not mention that the parameter cannot be null. This is strange, since Javadocs usually mentions when parameters cannot be null.

Is this just a glitch in the documentation or is there a more fundamental reason/twist I am missing?

Survance answered 23/8, 2011 at 22:55 Comment(1)
L
36

You can get some explanation when you look at the Comparable interface:

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.

Lamson answered 23/8, 2011 at 22:58 Comment(1)
my pleasure. I was looking for a nice way to exceed the 3.6 k of reputation today. ;)Lamson

© 2022 - 2024 — McMap. All rights reserved.