That's because of this code in String
class:
public static String valueOf(char data[]) {
return new String(data);
}
Your code (which throws NullPointerException
) calls the above-mentioned method and, thus, the data
field is null
. In fact, this call is thrown by the String
class on constructor.
Using JDK 6, the exception is as follows:
java.lang.NullPointerException
at java.lang.String.<init>(String.java:177)
at java.lang.String.valueOf(String.java:2840)
at org.bfs.data.SQLTexter.main(SQLTexter.java:364)
As for your line:
System.out.println(as+":"+as.length()); // prints: "null:4"
This works as the below method is called:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
Obviously, a
is of type Object
so the String.valueOf(Object)
method is called.
If you specifically want to call String.valueOf(Object obj)
method, typecast your null as follows:
System.out.println (String.valueOf((Object)null));
You're experiencing method overloading (where there are several method with the same name and method signature, but have different method parameters). In your case (where NPE occurs), the JVM determines which method to call based on the most specific static type. If the type is declared, then the most specific method is the method with the same parameter type of the declared variable, else, a most specific method rule is used by the JVM to find which method to invoke.
I hope this helps.