System.out.println()源码分析

如何理解System.out.println() ?

分析System源码

package java.lang;
public final class System {
}
  • System就是Java.lang包下一个类

out

 public final static PrintStream out = null;

public class PrintStream extends FilterOutputStream
    implements Appendable, Closeable
{
  • out是System里面的一个静态数据成员,而且这个成员是java.io.PrintStream类的引用
  • out已经存在了且用Static修饰了,所以可以直接使用类名+属性名的方式调用,也就是System.out。

println

public void println(boolean x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }
public void println(char x) {
        synchronized (this) {
            print(x);
            newLine();
        }
    }
//-----------------------
public void println() {
        newLine();
    }
  • println是PrintStream类中的方法,实现了重载,重写了基本数据类型的输入参数。
  • synchronized (this) 待分析
  • 调用了同类中的print方法
  • 调用了同类中的newLine()方法

 public void print(int i) {
        write(String.valueOf(i));
    }
    
  private void newLine() {
        try {
            synchronized (this) {
                ensureOpen();
                textOut.newLine();
                textOut.flushBuffer();
                charOut.flushBuffer();
                if (autoFlush)
                    out.flush();
            }
        }
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
            trouble = true;
        }
    }
  • print是PrintStream类中的方法,实现了重载,重写了基本数据类型的输入参数。
  • print将入口参数为基本数据类型的转化为String类型
  • print调用了同类中的write方法
 private void write(String s) {
        try {
            synchronized (this) {
                ensureOpen();
                textOut.write(s);
                textOut.flushBuffer();
                charOut.flushBuffer();
                if (autoFlush && (s.indexOf('\n') >= 0))
                    out.flush();
            }
        }
        catch (InterruptedIOException x) {
            Thread.currentThread().interrupt();
        }
        catch (IOException x) {
            trouble = true;
        }
    }
  • write调用了textOut
 private BufferedWriter textOut;
  • textOut是BufferedWriter里面的一个成员变量,而且这个成员是BufferedWriter类的引用
  • BufferedWriter继承与write类,也就是字符输出流。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值