JDK5.0 沿用了C語言庫函數中的printf方法,例如,如下:
System.out.printf("%8.2f",x);
可以用8個字符的寬度和小數點后兩位的精度打印x。
另外,以前我們向輸出當前日期,2006-5-10,需要使用DateFormat類,寫好幾行代碼,
現在:
System.out.printf("%tF",new Date());
輸出的就是2006-5-10
另外,相應的,String提供了format方法,用來格式化字符串。
String today = String.format("%tF",new Date());
System.out.println(today);
輸出結果也一樣。
其他格式控制符請查看文檔。