美文网首页
Java String是如何输出NULL的

Java String是如何输出NULL的

作者: atdoking | 来源:发表于2021-03-25 22:19 被阅读0次

1、对于申明的变量为String类型的,若其为空null,打印为空


image.png
image.png

主要在于print方法的实现,println方法是print和newline方法一起达到目的的,看源码可以发现

    /**
     * Prints a String and then terminate the line.  This method behaves as
     * though it invokes <code>{@link #print(String)}</code> and then
     * <code>{@link #println()}</code>.
     *
     * @param x  The <code>String</code> to be printed.
     */
    public void println(String x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }

print方法内部,当判断为空时,则赋值一个null字符串给变量,然后输出

    /**
     * Prints a string.  If the argument is <code>null</code> then the string
     * <code>"null"</code> is printed.  Otherwise, the string's characters are
     * converted into bytes according to the platform's default character
     * encoding, and these bytes are written in exactly the manner of the
     * <code>{@link #write(int)}</code> method.
     *
     * @param      s   The <code>String</code> to be printed
     */
    public void print(String s) {
        if (s == null) {
            s = "null";
        }
        write(s);
    }

2、对于申明的变量是一个非String类型的Object时,打印还是null


image.png

其原因还是print方法的另一个不同类型参数的重载实现,其内部会将该对应的转换成字符串,然后print方法内部,当判断为空时,则赋值一个null字符串给变量,然后输出

    /**
     * Prints an Object and then terminate the line.  This method calls
     * at first String.valueOf(x) to get the printed object's string value,
     * then behaves as
     * though it invokes <code>{@link #print(String)}</code> and then
     * <code>{@link #println()}</code>.
     *
     * @param x  The <code>Object</code> to be printed.
     */
    public void println(Object x) {
        String s = String.valueOf(x);
        synchronized (this) {
            print(s);
            newLine();
        }
    }

对于不同类型的其他变量,打印输出也大致是这个思路,然后打印出null

相关文章

网友评论

      本文标题:Java String是如何输出NULL的

      本文链接:https://www.haomeiwen.com/subject/yufdhltx.html