null object also has a toString() function?!

 

import static java.lang.System.out;

 

public class TestNull {

    public static void main(String[] args) {

        String s = null;

        String t = "";

        out.println(s);

        out.println(t);

        out.println(s + 1);

        out.println(t + 1);

    }

}

 

 

the output is: 

 

null

 

null1

1

Why out.println(s) doesn't throw an exception when s is null? 
Strange thingsI what happen? refer to this document:  http://stackoverflow.com/questions/271526/how-to-avoid-null-statements-in-java
Question:
=======================================

I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.

For instance:

System.out.println("obj: "+obj);

instead of:

System.out.println("obj: "+obj.toString());

Is there any difference apart from the null case?


Can the latter case work, when the former does not?

Edit:
What exactly is done, in case of the implicit call?

========================================

Answer:
========================================

There's little difference. Use the one that's shorter and works more often.

If you actually want to get the string value of an object for other reasons, and want it to be null friendly, do this:

String s = String.valueOf(obj);

The question was extended, so I'll extend my answer.

In both cases, they compile to something like the following:

System.out.println(new StringBuilder().append("obj: ").append(obj).toString());

When your toString() is implicit, you'll see that in the second append.

If you look at the source code to java, you'll see that StringBuilder.append(Object) looks like this:

public StringBuilder append(Object obj) {
   
return append(String.valueOf(obj));
}

where String.valueOf looks like this:

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

Now, if you toString() yourself, you bypass a null check and a stack frame and go straight to this inStringBuilder:

public StringBuilder append(String str) {
   
super.append(str);
   
return this;
}

So...very similar things happens in both cases. One just does a little more work.

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值