我是靠谱客的博主 慈祥电脑,这篇文章主要介绍记录String.valueOf()和toString()注意问题,现在分享给大家,希望可以做个参考。

  • toString()
    源码:
/**
     * This object (which is already a string!) is itself returned.
     *
     * @return  the string itself.
     */
    public String toString() {
        return this;
    }

返回对象本身,由于java.lang.Object类中也有toString()方法,对象也可调用此方法,需留意的是对象不能为空,会抛出NullPointerException异常

  • String.valueOf()
/**
     * Returns the string representation of the {@code Object} argument.
     *
     * @param   obj   an {@code Object}.
     * @return  if the argument is {@code null}, then a string equal to
     *          {@code "null"}; otherwise, the value of
     *          {@code obj.toString()} is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

这里不需要注意Object为null的情况,但要留意,如果对象为空,返回的是"null"值,不是null

最后

以上就是慈祥电脑最近收集整理的关于记录String.valueOf()和toString()注意问题的全部内容,更多相关记录String内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(45)

评论列表共有 0 条评论

立即
投稿
返回
顶部