在java中,当我们定义一个字符数组想要输出时,可以直接在输出语句中写上它的应用即可,为什么可以这样呢?首先我们看一下下面的这个例子!
package cn.edu.ahui; public class TestDemo { public static void main(String[] args){ char[] c ={'a','b','c'}; String s = new String("Leo"); String[] s2 = {"aa","bb","cc"}; System.out.println(c); System.out.println(c.toString()); System.out.println(s); System.out.println(s.toString()); System.out.println(s2); System.out.println(s2.toString()); } } 这段代码的输出结果如下:abc [C@1db9742 Leo Leo [Ljava.lang.String;@106d69c [Ljava.lang.String;@106d69c
从输出的结果我们可以看出,输出字符数组可以直接在输出语句中加上它的应用即可。我们从源码开始分析!
System.out.println(c);方法最终调用的是PrintStream类的write(char buf[])方法,见下面代码
private void write(char buf[]) { try { synchronized (this) { ensureOpen(); textOut.write(buf); textOut.flushBuffer(); charOut.flushBuffer(); if (autoFlush) { for (int i = 0; i < buf.length; i++) if (buf[i] == '\n') out.flush(); } } } textOut是BufferedWriter对象,代表着向控制台输出信息的输出流对象.charOut是OutputStreamWriter对象,是用来将字节转换成字符的转换流对象.textOut包装了charOut. textOut.write(buf);调用到以下方法:
public void write(char cbuf[]) throws IOException { write(cbuf, 0, cbuf.length); } 该方法就是将char数组的每个字符挨个输出到控制台中啦. 总结一句话,其System.out.println(c);就是将c数组的每个字符挨个输出到控制台中.
其他语句类似这样分析。
