What is the difference between System.out.println and System.out.print in Java?

Source: Internet
Author: User

The common console output statements in Java are System.out.println and System.out.print

One: The difference between the two is as follows:

1. There are different parameters:

SYSTEM.OUT.PRINTLN () can not write parameters

The System.out.print (parameter) parameter cannot be empty. Must have

2. The effect is different

PRINTLN: Wraps the message after the output is finished, producing a new line

Print: No new rows are generated

3.PRINTLN more concise, print more flexible

Print can be followed by "\ n" to achieve the same effect as println

You can also follow the "\ T" tab, and so on.

Second: Read Java source code to understand

SYSTEM.OUT.PRINTLN (string parameter); The source code is as follows

123456  public voidprintln(String x) {        synchronized(this) {            print(x);//先调用print(x)来打印信息            newLine();//然后换行        }    }

System.out.print (string parameter); The source code is as follows

123456  publicvoidprint(String s) {        if(s == null) {            s = "null";        }        write(s);    }

Three things to note: although there is a slight difference, but two methods are often used together, more flexible and convenient.

Four reference examples and annotations

When we output an array of elements, we often do not want to output 1 for each line 1 times, generally we will be in the output array before the line, the output is finished before wrapping again.

12345678910 public classOutDemo {    publicstaticvoidmain(String[] args) {        String[] name = {"tom","jack","jerry","lucy"};        System.out.println("-------输出信息------");//输出完信息后换行        for(inti = 0; i < name.length; i++) {            System.out.print(name[i]+" ");//输出元素,并且追加1个空白,用于隔开元素        }        System.out.println("\n-------------------");// "\n"先输出换行,然后输出信息,最后再换行    }}

Effect

123 -------输出信息------tom jack jerry lucy -------------------

What is the difference between System.out.println and System.out.print in Java?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.