why valueOf(null) calls the constructor valueOf(char[])

130 Views Asked by At
String.valueOf(null);
  1. why valueOf(char[] c) is called and why not valueOf(Object o); ??
  2. Why String.valueOf(null); produces a NullPointerException and String.valueOf((Object)null); do not produce any exception?
2

There are 2 best solutions below

1
On

String.valueOf((Object) null) calls the following method:

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

As you can see, the null case is managed.

String.valueOf(null) calls the following method:

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

Which itself calls:

public String(char value[]) {
    this.offset = 0;
    this.count = value.length; // <-- NPE
    this.value = StringValue.from(value);
}
1
On

Whenever more than one overloaded methos would be a possible target the most specific one possible would be used.

So if you pass in a char[] then valueOf(char[]) and valueOf(Object) would be possible, but valueOf(char[]) is more specific. Therefore that one will be called.

Now null is kind-of strange because it's a legal value for every non-primitive type, so it could be an argument to any of those methods. And still valueOf(char[]) is more specific than valueOf(Object), therefore the first one will be called.