java valueof null,String.valueOf(null) 遇到的坑

说说关于String.valueOf的这个坑。

public class TestString {

public static void main(String[] args){

Object obj = null;

System.out.println(String.valueOf(obj));

System.out.println(String.valueOf(null));

}

}

这段代码,第一个输出“null”,没错,不是空对象null也不是空串“”,而是一个字符串!!包含四个字母n-u-l-l的字符串...

第二个输出,咋一看没差别,但是,第二个输出,抛空指针异常了。

下面来分析分析原因。

先说第一个:

看第一个的源码实现:

/**

* Returns the string representation of the Object argument.

*

* @param obj an Object.

* @return if the argument is null, then a string equal to

* "null"; otherwise, the value of

* obj.toString() is returned.

* @see java.lang.Object#toString()

*/

public static String valueOf(Object obj) {

return (obj == null) ? "null" : obj.toString();

}

源码很简单,如果对象为空,就返回字符串的"null"...不为空就调用toString方法。

再来说第二个:

第二个和第一个的不同,是java对重载的不同处理导致的。

基本类型不能接受null入参,所以接受入参的是对象类型,如下两个:

String valueOf(Object obj)

String valueOf(char data[])

这两个都能接受null入参,这种情况下,java的重载会选取其中更精确的一个,所谓精确就是,重载方法A和B,如果方法A的入参是B的入参的子集,则,A比B更精确,重载就会选择A。换成上面这两个就是,char[]入参的比object的更精确,因为object包含char[],所以String.valueOf(null)是用char[]入参这个重载方法。

看看这个方法的实现:

/**

* Returns the string representation of the char 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 char 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);

}

直接new String的,再看new String的实现:

/**

* Allocates a new {@code String} so that it represents the sequence of

* characters currently contained in the character array argument. The

* contents of the character array are copied; subsequent modification of

* the character array does not affect the newly created string.

*

* @param value

* The initial value of the string

*/

public String(char value[]) {

this.value = Arrays.copyOf(value, value.length);

}

第12行,入参为null,null.length就报NPE了。

大家用的时候养成多看源码实现的好习惯,可以避免踩坑...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值