Even a chimp can write code

Tuesday, January 25, 2005

Questionable String.valueOf implementation

My obsession with Strings continues. I just came across an inexplicable anomaly in the java.lang.String class.

int[] numbers = null;

char[] characters = null;

These two String.valueOf() method calls display different behavior. The former displays a "null" string. The latter, being rather quixotic, throws a NullPointerException. If there's a good reason for this divergence (I have a hunch there is), it isn't immediately apparent. Can someone please shed some light?

Email this | Bookmark this


  • From the Java source:

    public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();

    public static String valueOf(char data[]) {
    return new String(data);

    By Blogger Jonathan Feinberg, at January 25, 2005 at 7:04 PM  

  • This comment has been removed by a blog administrator.

    By Blogger Ashish, at January 26, 2005 at 4:55 AM  

  • the behavior you mention has been submitted as bugs several times in sun's java bug database:


    seems as though they aren't gonna fix the inconsistency because of "compatibility concerns". even just changing the javadoc to warn of NPE would satisfy me...

    By Blogger Paul Holser, at January 26, 2005 at 9:05 AM  

Post a Comment | Home | Inference: my personal blog