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类,也就是字符输出流。
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务