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?