黑马程序员技术交流社区

标题: System.out.println()和System.out.print("\n")区别 [打印本页]

作者: 刘朋朋    时间: 2011-10-7 17:53
标题: System.out.println()和System.out.print("\n")区别
本帖最后由 刘朋朋 于 2011-10-7 17:53 编辑

他们的功能是一样的吧?但是又有什么差异呢?
作者: 许晨峰    时间: 2011-10-7 17:57
要看在什么操作系统上执行了。
linux或unix系统,效果相同。而Window系统,是不同的,window的是System.out.println()和System.out.print("\r\n")一样,一般可以通过String str = System.getProperty("line.separator");来获得这个行尾结束字符串
作者: 刘朋朋    时间: 2011-10-7 18:00
LS的,谢谢了~~~~~~{:soso_e189:}
作者: zhousaowen    时间: 2011-10-7 18:06
你可以调试一下,效果是一样啊!
查文档:println
public void println()通过写入行分隔符字符串终止当前行。行分隔符字符串由系统属性 line.separator 定义,不一定是单个换行符 ('\n')。
查看源码:
/**
     * Terminates the current line by writing the line separator string.  The
     * line separator string is defined by the system property
     * <code>line.separator</code>, and is not necessarily a single newline
     * character (<code>'\n'</code>).
     */
    public void println() {
        newLine();
    }

自己去体验下!
作者: 许晨峰    时间: 2011-10-7 19:30
刘朋朋 发表于 2011-10-7 18:00
LS的,谢谢了~~~~~~

客气啥,都是兄弟。
作者: 王家俊    时间: 2011-10-7 23:03
System.out.println()中的println方法的原始代码如下:
public void println(String x) {
        synchronized (this) {
            print(x);
            newLine();
        }
从中可以看出有newLine()方法,此方法可以在打印完行后自动换行。
而System.out.pirnt()中的方法print()的源码如下:
public void print(String s) {
        if (s == null) {
            s = "null";
        }
        write(s);
    }
从中可以看出没有换行方法,但由于操作系统知道"\n"表示的是换行,所以System.out.print("\n")也可以换行。
作者: 陈晓东    时间: 2011-10-8 01:01
System.out.println()是根据系统自动选择换行符且println()源代码有{newline()}这样一句。 这个意思就是换行。在BufferReader类中也有一个这样的方法newLine
public void newLine()
             throws IOException写入一个行分隔符。行分隔符字符串由系统属性 line.separator 定义,并且不一定是单个新行 ('\n') 符。

System.out.print("\n")需要根据系统手动输入换行符。windos系统是"\r\n"  Linux系统是"\n"。
作者: 黄新灵    时间: 2011-10-8 11:03
String str = System.getProperty("line.separator");
System.out.println()==System.out.print(str)
作者: 李文肖    时间: 2011-10-8 11:10
System.out.println()功能是输出并换行;
System.out.print()功能是输出但不换行.




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2