怎么理解System.out.println()的机制

怎么理解System.out.println()的机制

直接上源码

public void println(String x) {
        if (getClass() == PrintStream.class) {
            writeln(String.valueOf(x));
        } else {
            synchronized (this) {
                print(x);
                newLine();
            }
        }
    }

先判断是不是类,如果不是(也就是数字、字符、字符串等),直接调用print()方法输出再调用newLine()方法换行输出。
如果是,调用valueOf()方法。
valueOf源码:

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

在调用后,先判断obj是否为null。

1、是空串

如果为null,那么返回字符串“null”!注意,这你返回的时字符串“null”,而不是空串!也就是说,下面这段代码:

String str1=null;
String str2="null";
System.out.println(str1);
System.out.println(str2);

这段代码输出结果将为:

null
null

也就是说不会使得输出为空,对于字符串的连接也是一个道理。

2、不是空串

如果不是null,那么将会执行toString()方法,其源码如下:

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

大概的意思是输出 类名+@+内容;如果obj是个类,内容就是地址。

3、为什么要重写toString

很多类里边都会重写toString方法,就是为了更方便的输出。比如:

public class sample{
	int a;
	int b;
	public sample(int x,int y){ a=x;b=y}
	@override
	public String toString(){
		return String.format("(a,b)=(%d,%d)",a,b);
	}
	public static void main(String[] args){
		sample s=new sample(10,20);
		System.out.println(s);
	}
}

代码将输出:

(a,b)=(10,20)

版权声明:本文为weixin_44595525原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。