JAVA的System.out.println和System.out.printf之间有什么区别?
生活随笔
收集整理的這篇文章主要介紹了
JAVA的System.out.println和System.out.printf之间有什么区别?
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
平時我們編寫代碼大多都是使用System.out.println或者System.out.print。
printf???相信學過C語言的應該知道這個輸出語句關鍵字。
那java中的System.out.printf是???
好像還真沒考慮過。前往它出生的地方:
我們看到他們都是PrintStream中的方法。
printf部分源碼:
/*** A convenience method to write a formatted string to this output stream* using the specified format string and arguments.** <p> An invocation of this method of the form <tt>out.printf(format,* args)</tt> behaves in exactly the same way as the invocation** <pre>* out.format(format, args) </pre>** @param format* A format string as described in <a* href="../util/Formatter.html#syntax">Format string syntax</a>** @param args* Arguments referenced by the format specifiers in the format* string. If there are more arguments than format specifiers, the* extra arguments are ignored. The number of arguments is* variable and may be zero. The maximum number of arguments is* limited by the maximum dimension of a Java array as defined by* <cite>The Java™ Virtual Machine Specification</cite>.* The behaviour on a* <tt>null</tt> argument depends on the <a* href="../util/Formatter.html#syntax">conversion</a>.** @throws java.util.IllegalFormatException* If a format string contains an illegal syntax, a format* specifier that is incompatible with the given arguments,* insufficient arguments given the format string, or other* illegal conditions. For specification of all possible* formatting errors, see the <a* href="../util/Formatter.html#detail">Details</a> section of the* formatter class specification.** @throws NullPointerException* If the <tt>format</tt> is <tt>null</tt>** @return This output stream** @since 1.5*/public PrintStream printf(String format, Object ... args) {return format(format, args);}println部分源碼
/*** Prints a String and then terminate the line. This method behaves as* though it invokes <code>{@link #print(String)}</code> and then* <code>{@link #println()}</code>.** @param x The <code>String</code> to be printed.*/public void println(String x) {synchronized (this) {print(x);newLine();}}分析得出:
無論是print還是println返回值均為void,
println如果輸出某參數時,內部調用print(這個參數)然后調用newLine。
并且這兩者參數都是只有一個,比如基本數據類型的某一種,或者對象,數組等。
而printf就不一樣了,源碼上給出的解釋是:
使用指定的格式字符串和參數將格式化字符串寫入此輸出流的方便方法。
對于printf,有兩個方法
舉個例子:
可以這樣說,在輸出上,
// System.out.printf("%d\t",data);System.out.print(data + "\t");這兩代碼的輸出結果是一致的。
一個小知識點而已,不過既然遇到了,記錄一下。
總結
以上是生活随笔為你收集整理的JAVA的System.out.println和System.out.printf之间有什么区别?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JAVA数据结构与算法【简单介绍】
- 下一篇: JAVA数据结构与算法【稀疏数组】