I just found something interesting.
public class test {
public static void main(String a[])
{
System.out.println(String.valueOf(null).length());
}
}
Output
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.<init>(Unknown Source)
This is what I kind of expected.
But when i run this
public class test {
public static void main(String a[])
{
String s=null;
System.out.println(String.valueOf(s).length());
}
}
Output
4
There are two overloaded version of valueOf which gets called,they are
/**
* Returns the string representation of the <code>Object</code> argument.
*
* @param obj an <code>Object</code>.
* @return if the argument is <code>null</code>, then a string equal to
* <code>"null"</code>; otherwise, the value of
* <code>obj.toString()</code> is returned.
* @see java.lang.Object#toString()
*/
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
/**
* Returns the string representation of the <code>char</code> array
* argument. The contents of the character array are copied; subsequent
* modification of the character array does not affect the newly
* created string.
*
* @param data a <code>char</code> array.
* @return a newly allocated string representing the same sequence of
* characters contained in the character array argument.
*/
public static String valueOf(char data[]) {
return new String(data);
}
I didn't get why valueOf(Object s) method is giving special treatment to null. Thoughts/Comments?